|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.HashSet; |
| 3 | +import java.util.List; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.Set; |
| 6 | + |
| 7 | +// DFS ์์ ํ์ํ ๋ ๋ถํ์ํ ํ์์ ์ค์ด๋ ๋ฐฉ๋ฒ์ ํญ์ ๊ณ ๋ฏผํ ๊ฒ. |
| 8 | +class Solution { |
| 9 | + public int size = 0; |
| 10 | + public Map<String, Boolean> failedMap = new HashMap<>(); |
| 11 | + public boolean wordBreak(String s, List<String> wordDict) { |
| 12 | + size = wordDict.size(); |
| 13 | + |
| 14 | + Set<Character> sSet = new HashSet<>(); |
| 15 | + for (char c : s.toCharArray()) { |
| 16 | + sSet.add(c); |
| 17 | + } |
| 18 | + |
| 19 | + Set<Character> wSet = new HashSet<>(); |
| 20 | + for (char c : String.join("", wordDict).toCharArray()) { |
| 21 | + wSet.add(c); |
| 22 | + } |
| 23 | + |
| 24 | + if(sSet.size() > wSet.size()) { |
| 25 | + return false; |
| 26 | + } |
| 27 | + |
| 28 | + return dfs(s, wordDict); |
| 29 | + } |
| 30 | + |
| 31 | + public boolean dfs(String s, List<String> wordDict) { |
| 32 | + if(s.length() == 0) return true; |
| 33 | + if(failedMap.containsKey(s)) return false; |
| 34 | + |
| 35 | + for(int i = 0; i < size; i++) { |
| 36 | + String word = wordDict.get(i); |
| 37 | + if(s.startsWith(word)) { |
| 38 | + |
| 39 | + s = s.substring(word.length()); |
| 40 | + boolean result = dfs(s, wordDict); |
| 41 | + |
| 42 | + if(result) { |
| 43 | + return true; |
| 44 | + } else { |
| 45 | + failedMap.put(s, true); |
| 46 | + } |
| 47 | + |
| 48 | + s = word + s; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return false; |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// ํน์ ๋ฌธ์๋ก ์์๋๋ ๊ฒ๋ง ํ๋จํ์ฌ ๋ฐ๋ณตํด ํ๋ ค๊ณ ํ๋ ์ ๊ทผ๋ฒ. |
| 57 | +// ์ ์ฒด ์กฐํฉ์ ๋ณด์์ผ ํ๋ "cars", ["cars", "ca", "rs"] ๊ฒฝ์ฐ์ ๋ฐ๋ก๊ฐ ๋จ. |
| 58 | +class WrongSolution { |
| 59 | + public boolean wordBreak(String s, List<String> wordDict) { |
| 60 | + int size = wordDict.size(); |
| 61 | + |
| 62 | + while(true) { |
| 63 | + boolean isMatched = false; |
| 64 | + for(int i = 0; i < size; i++) { |
| 65 | + String word = wordDict.get(i); |
| 66 | + if(s.startsWith(word)) { |
| 67 | + isMatched = true; |
| 68 | + s = s.substring(word.length()); |
| 69 | + break; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + if(!isMatched) { |
| 74 | + break; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return s.length() == 0; |
| 79 | + } |
| 80 | +} |
0 commit comments