LeetCode 1002(競争問題):共通文字(小文字のみからなる文字列配列Aを指定し、リスト内の各文字列に表示されるすべての文字(重複文字を含む)からなるリストを返します.)
小文字のみからなる文字列配列Aが与えられ、リスト内の各文字列に表示されるすべての文字(重複文字を含む)からなるリストが返される.たとえば、1つの文字が各文字列に3回表示され、4回ではない場合は、最終的な答えに3回含まれる必要があります.任意の順序で答えを返すことができます.
例1:入力:[bella,label,roller]出力:[e,l,l]
例2:入力:[cool],[lock],[cook]出力:[c],[o]
全体的な考え方:文字列配列の最初の文字列で残りの文字列と比較し、共通の文字を見つけ、最小重複数を計算し、集合に伝えることです.
例1:入力:[bella,label,roller]出力:[e,l,l]
例2:入力:[cool],[lock],[cook]出力:[c],[o]
全体的な考え方:文字列配列の最初の文字列で残りの文字列と比較し、共通の文字を見つけ、最小重複数を計算し、集合に伝えることです.
import java.util.*;
public class lianxi{
public static void main(String[] args){
Solution S = new Solution();
String[] A = {"bella","label","roller"};
List list = S.commonChars(A);
System.out.println(list);
}
}
class Solution {
public List commonChars(String[] A) {
List list = new ArrayList<>();
for(int j = 0; j < A[0].length(); j++){
//
int count = 0;//
char c = 'a';
for(int i = 0; i < A.length-1; i++){
//
int a = rechecking(A[0].charAt(j),A[i]);
int b = rechecking(A[0].charAt(j),A[i+1]);
c = A[0].charAt(j);
if(a==0||b==0){
// a b 0 count
count =0;
break;
}
if(count == 0){
// a b
if(a >= b){
count = b;
}
else{
count = a;
}
}
else{
//count 0 a,b,count ,
if(a >= b){
if(count > b){
count = b;
}
}
else{
if(count > a ){
count = a;
}
}
}
}
if(list.contains(String.valueOf(c)) == false && count > 0 ){
//
while(count > 0){
list.add(String.valueOf(c));
count--;
}
}
}
return list;
}
public int rechecking(char chars, String s){
//
int count = 0;
for(int i = 0; i < s.length(); i++){
if(chars == s.charAt(i)){
count++;
}
}
return count;
}
}