判斷兩個字符串是否有相同字符(每個字母的個數也相同)組成
阿新 • • 發佈:2018-08-22
bbc 初始 pre util abc 字符 sta ray public 初始化一個字符串數組 每個位賦值為0 即 0000 0000 0000 0000...
對第一個字符串 s1 轉成的每個字節 如425154 在對應位置上加1
如4則在 第四的位置加1 0001 0000 0000 0000 ...
對第二個字符串 s2 轉成的每個字節 如425154 在對應位置上則減1
最後只要 這個數組有一個元素不等於0 則說明 2個字符串不相等
對第一個字符串 s1 轉成的每個字節 如425154 在對應位置上加1
如4則在 第四的位置加1 0001 0000 0000 0000 ...
對第二個字符串 s2 轉成的每個字節 如425154 在對應位置上則減1
最後只要 這個數組有一個元素不等於0 則說明 2個字符串不相等
import java.util.Arrays; //空間換時間 public class Test_plus { public static void compare(String s1,String s2) { byte[]b1=s1.getBytes(); byte[]b2=s2.getBytes(); int[]bCount=new int[256]; for(int i=0;i<256;i++) { bCount[i]=0; } for(int i=0;i<b1.length;i++) bCount[b1[i]-‘0‘]++; for(int i=0;i<b2.length;i++) bCount[b2[i]-‘0‘]--; for(int i=0;i<256;i++) if(bCount[i]!=0) { System.out.println("not equal"); return; } System.out.println("equal"); } public static void main(String[] args) { String s1="aaabbc"; String s2="abcbaaa"; compare(s1, s2); s1="aaaabbc"; s2="abcbaab"; compare(s1, s2); } }
判斷兩個字符串是否有相同字符(每個字母的個數也相同)組成