如何比较两个字符串如果它们被重新排列

use*_*852 4 java string equals char

我想知道如何比较两个重新排列的字符串例如,如果字符串a ="字符串",字符串b ="tsrngi"...如果我比较a.equals(b),它将返回false,因为字符的顺序.我希望它返回true,因为字符相同但只是顺序不同..谢谢

JRL*_*JRL 8

对它们进行排序,然后进 要排序,请使用以下内容:

char[] content = unsorted.toCharArray();
java.util.Arrays.sort(content);
String sorted = new String(content);
Run Code Online (Sandbox Code Playgroud)

  • 它很优雅,但对于一个应该采用"O(n)"的操作也需要"O(n lg n)". (2认同)

cor*_*iKa 6

我非常喜欢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)