对它们进行排序,然后进 要排序,请使用以下内容:
char[] content = unsorted.toCharArray();
java.util.Arrays.sort(content);
String sorted = new String(content);
Run Code Online (Sandbox Code Playgroud)
我非常喜欢JRL的解决方案,因为它非常优雅.与此同时,我觉得因为有一个解决方案是复杂的顺序,我应该分享它.它不那么优雅,但它O(n)不是O(n lg n).
if(str1.length() != str2.length()) return false;
Map<Character, Integer> counts = new HashMap<Character, Integer>();
for(int i = 0; i < str1.length(); i++) {
// add 1 for count for str1
if(counts.contains(str1.charAt(i)) {
counts.put(str1.charAt(i),counts.get(star1.charAt(i)) + 1);
} else {
counts.put(str1.charAt(i),1);
}
// sub 1 for count for str2
if(counts.contains(str2.charAt(i)) {
counts.put(str2.charAt(i),counts.get(str2.charAt(i)) - 1);
} else {
counts.put(str2.charAt(i),-1);
}
}
// when you're done, all values in the map should be 0. If they
// aren't all 0, you don't have equal-arranged strings.
for(Integer i : counts.values()) {
if(i.intValue() != 0) return false;
}
// we made it this far, we know it's true
return true;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1020 次 |
| 最近记录: |