描述
判斷兩個字符串是否由相同的字符組成
分析
方法一,排序法。對兩個字符串進行排序,然后在比較。
方法二,空間換時間。ascII字符共256個,對字符串1出現的字符在對應的數組里加1,對字符串1出現的字符在對應的數組里減1。
代碼
方法一 排序法。
public class Test { public static boolean compare(String s1,String s2){ if(s1.length()!=s2.length()) return false; byte[] byte1=s1.getBytes(); byte[] byte2=s2.getBytes(); Arrays.sort(byte1); Arrays.sort(byte2); for(int i=0;i<s1.length();i++){ if(byte1[i]!=byte2[i]) return false; } return true; } public static void main(String[] args) { System.out.println(compare("zayyyy","zayyyy")); } }
方法二,空間換時間。
public class Test { public static boolean compare(String s1,String s2){ if(s1.length()!=s2.length()) return false; byte[] byte1=s1.getBytes(); byte[] byte2=s2.getBytes(); int[] charCount=new int[256]; //ascII 字符共有266個。 for(int i=0;i<s1.length();i++){ charCount[byte1[i]]++; charCount[byte2[i]]--; } for(int i:charCount){ if(i!=0) return false; } return true; } public static void main(String[] args) { System.out.println(compare("zayyyy","zayyyb")); } }
