-
Notifications
You must be signed in to change notification settings - Fork 0
/
1002. Find Common Characters.java
64 lines (44 loc) · 1.61 KB
/
1002. Find Common Characters.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
1002. Find Common Characters.
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Input: ["cool","lock","cook"]
Output: ["c","o"]
*/
class Solution {
public List<String> commonChars(String[] A) {
int stringMinLength = 32000;
List<List<String>> givenStrings = new ArrayList<List<String>>();
ArrayList<String> answer = new ArrayList<String>();
// Transformation is required for easy removal and searching
for(int i = 0; i < A.length; i++){
int thisStringLength = A[i].length();
if(thisStringLength < stringMinLength){
stringMinLength = thisStringLength;
}
List<String> charsInString = new ArrayList<>(Arrays.asList( A[i].split("") ));
givenStrings.add( charsInString );
}
//System.out.println(stringMinLength);
for(int j = 0; j < stringMinLength; j++){
String currStr = givenStrings.get(0).get(0);
//System.out.println(currStr);
boolean containsInAll = true;
for(int k = 0; k < givenStrings.size(); k++){
int indexOf = givenStrings.get(k).indexOf(currStr);
if(indexOf >= 0 ){
givenStrings.get(k).remove(indexOf);
}else{
containsInAll = false;
break;
}
}
if(containsInAll){
answer.add(currStr);
}
}
return answer;
}
}