2024年4月6日 星期六

[leetcode] [eazy] Q1002

public class Q1002 {
public static void main(String[] args) {
String[] words = {"bella","label","roller"};
commonChars(words);
}
public static List<String> commonChars(String[] words) {
List<String>ans = new ArrayList<>();
int[] count = new int[26];
Arrays.fill(count, Integer.MAX_VALUE);
for(String str: words){
int []cnt = new int[26];
str.chars().forEach(c->++cnt[c-'a']);
for(int i= 0; i<26; i++){
count[i] = Math.min(cnt[i], count[i]);
}
}
for(char c='a'; c<='z';c++){
while(count[c-'a']-->0){
ans.add("" + c);
}
}
return ans;
}
}

1 Arrays.fill方法沒用過, 可以用來產生空陣列


2 統計文出現次數可以用int[]count = new int[26]]


3 str.chars().forEach(c->++cnt[c-'a'])

可以用來把cnt陣列中出現的文母次數做一個統計


4 for(char c=='a';c<='z';c++){

while(count[c-'a']-->0){

ans.add(""+c);

}

}

能將陣列中出現的字母, 在轉換放進List答案中


eazy這麼難...

 

沒有留言:

張貼留言

[leetcode] [KMP] KMP

ABCDABD... ABCDABF... 簡單的說, 傳統解兩字串匹配部分 可能會來個雙迴圈, 哀個比對, 當不匹配的時候, 會將下方列再後移1位 然後不匹配再後移 然而 如果像上放已經有4個屬於匹配的字串, 她就應該直接往後移四位來匹配, 而不是只移動1位 隱藏的思維是, 當...