[英]How To Compare Two Strings If they are rearranged
我想知道如何比较两个重新排列的字符串例如,如果字符串a =“字符串”,字符串b =“tsrngi”...如果我比较a.equals(b),它将返回false,因为字符的顺序。我希望它返回true,因为字符相同但只是顺序不同..谢谢
Sort them, then compare. 对它们进行排序,然后进 To sort, use something like: 要排序,请使用以下内容:
char[] content = unsorted.toCharArray();
java.util.Arrays.sort(content);
String sorted = new String(content);
I really like JRL's solution, since it's quite elegant. 我非常喜欢JRL的解决方案,因为它非常优雅。 At the same time, I feel that because there is a solution that is an order of complexity better that I should share it. 与此同时,我觉得因为有一个解决方案是复杂的顺序,我应该分享它。 It's less elegant, but it's O(n)
instead of O(n lg n)
. 它不太优雅,但它是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(str1.charAt(i)) {
counts.put(str1.charAt(i),counts.get(star1.charAt(i)) - 1);
} else {
counts.put(str1.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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.