public static boolean stringSame(String str1,String str2){ if(str1.length() != str2.length()){//先判断长度 return false; } StringBuffer strTemp = new StringBuffer();//把str2放到一个StringBuffer strTemp.append(str2); for(int i = 0;i < str1.length();i++){//循环字符串1的字符,查看字符串2是否有相同字符,有的话删除 char temp = str1.charAt(i); int index = strTemp.toString().indexOf(temp); if(index != -1){ strTemp.deleteCharAt(index); }else{ return false; } } if(strTemp.toString().length() == 0){//删除结束,确认长度为0则相等 return true; } return false; }
//第二种解法 public static equals(String s1,String s2){ if (s1.length() != s2.length()) return false; if (s1.equals(s2)) return true; if (s1 == s2) return true; char[] ca1 = s1.toCharArray(); char[] ca2 = s2.toCharArray(); Arrays.sort(ca1); Arrays.sort(ca2); return Arrays.equals(ca1,ca2); }