判斷兩字串的字符集是否相同《演算法很美》
阿新 • • 發佈:2021-01-02
判斷兩字串的字符集是否相同
思路: 就是s1中出現的ASCII的字符集 與 s2出現的ASCII的字符集進行對比,檢視是否相同。
public class 判斷兩字串的字符集是否相同 {
/*
* 限制串的組成的字元時ASCII
*
* */
static boolean check(String s1,String s2){
int[] help = new int[256];
//掃描s1
for (int i = 0; i < s1.length( ); i++) {
char c = s1.charAt(i);
if (help[c]==0)
help[c]=1;
}
//掃描s2
for (int i = 0; i < s2.length(); i++) {
char c = s2.charAt(i);
if (help[c]==0)
return false;
}
return true;
}
static boolean check2(String s1,String s2){
Map<Character,Integer> map = new HashMap<Character, Integer>();
//掃描s1
for (int i = 0; i < s1.length(); i++){
char c = s1.charAt(i);
if (map.get(c)==null){
map.put(c,1);
}
}
//掃描s2
for (int i = 0; i < s2.length(); i++){
char c = s2.charAt(i);
if (map.get(c)==null)//這說明c不在map的key列表中
return false;
}
return true;
}
public static void main(String[] args){
boolean res = check2("abcde","deabccadcd");
System.out.println(res);
}
}
知識點:
Map<Character,Integer> map = new HashMap<Character, Integer>();
宣告HashMap物件,Character 類用於對單個字元進行操作。- map.put(c,1);新增資料
- map.get©;獲取資料