https://leetcode.com/problems/find-common-characters/
| 7 | * https://leetcode.com/problems/find-common-characters/ |
| 8 | */ |
| 9 | public class Sanghoo { |
| 10 | |
| 11 | // 첫 문자열을 기준 삼아 각 문자가 모두 포함이 되어있으면 res에 추가 및 해당 문자 삭제하는 방식으로 접근 |
| 12 | public static List<String> commonChars(String[] words) { |
| 13 | List<String> res = new ArrayList<String>(); |
| 14 | |
| 15 | // 삭제를 쉽게 하기 위해 StringBuilder 사용 |
| 16 | List<StringBuilder> list = new ArrayList<StringBuilder>(); |
| 17 | for(String word : words) { |
| 18 | list.add(new StringBuilder(word)); |
| 19 | } |
| 20 | |
| 21 | StringBuilder standard = list.get(0); // 기준이 되는 첫 번째 문자열 |
| 22 | |
| 23 | for(int i=0; i<standard.length(); i++) { |
| 24 | String ch = String.valueOf(standard.charAt(i)); |
| 25 | int index = 0; |
| 26 | |
| 27 | // 각 배열을 돌면서 하나라도 해당 문자(ch)가 없으면 break |
| 28 | for(int j=1; j<list.size(); j++) { |
| 29 | index = list.get(j).indexOf(ch); |
| 30 | if(index == -1) { |
| 31 | break; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | // 해당 문자(ch)가 모두 포함 되었다면 |
| 36 | if(index != -1) { |
| 37 | // 각 문자열에서 해당 문자의 위치를 찾아 삭제 및 res 추가 |
| 38 | for(int k=1; k<list.size(); k++) { |
| 39 | int deleteIndex = list.get(k).indexOf(ch); |
| 40 | list.get(k).deleteCharAt(deleteIndex); |
| 41 | } |
| 42 | res.add(ch); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | return res; |
| 47 | } |
| 48 | |
| 49 | public static void main(String[] args) { |
| 50 | String[] words = {"dbaabcba","cabcdbab","cdbcbdad","abadbacc","bdddddaa","daddabab","baaaddaa","dccdaabd"}; |
| 51 | System.out.println(commonChars(words)); |
| 52 | } |
| 53 | } |
nothing calls this directly
no outgoing calls
no test coverage detected