139. word split

    public boolean wordBreak(String s, List<String> wordDict) {
        return wordBreakSet(s, new HashSet<>(wordDict));
    }

    private boolean wordBreakSet(String s, HashSet<String> wordDict) {
        if (s.isEmpty()) {
            return true;
        }
        for (int i = 0; i < s.length(); i++) {
            String before = s.substring(0, i);
            String after = s.substring(i);
            if (wordDict.contains(after) && wordBreakSet(before, wordDict)) {
                return true;
            }
        }
        return false;
    }
  • Recursive + memory accept, time complexity: O (N ^ 2), the spatial complexity of O (N): the depth of recursion
public boolean wordBreak(String s, List<String> wordDict) {
        return wordBreakSet(s, new HashSet<>(wordDict), new HashSet<>());
    }

    private boolean wordBreakSet(String s, HashSet<String> wordDict, HashSet<String> memory) {
        if (s.isEmpty()) {
            return true;
        }
        if (memory.contains(s)) return false; //记忆
        for (int i = 0; i < s.length(); i++) {
            String before = s.substring(0, i);
            String after = s.substring(i);
            if (wordDict.contains(after) && wordBreakSet(before, wordDict, memory)) {
                return true;
            }
        }
        memory.add(s); //记忆
        return false;
    }
  • Simple BFS, overtime
public boolean wordBreak(String s, List<String> wordDict) {
        LinkedList<String> queue = new LinkedList<>();
        queue.add(s);
        while (!queue.isEmpty()) {
            String seg = queue.poll();
            for (String word : wordDict) {
                if (seg.startsWith(word)) {
                    String otherSeg = seg.substring(word.length());
                    if (otherSeg.isEmpty()) {
                        return true;
                    }
                    queue.add(otherSeg);
                }
            }
        }
        return false;
    }
  • BFS + memory, accept
public boolean wordBreak(String s, List<String> wordDict) {
        LinkedList<String> queue = new LinkedList<>();
        queue.add(s);
        Set<String> memory = new HashSet<>(); //记忆
        while (!queue.isEmpty()) {
            String seg = queue.poll();
            if (!memory.contains(seg)) { //记忆
                for (String word : wordDict) {
                    if (seg.startsWith(word)) {
                        String otherSeg = seg.substring(word.length());
                        if (otherSeg.isEmpty()) {
                            return true;
                        }
                        queue.add(otherSeg);
                    }
                }
                memory.add(seg); //记忆
            }
        }
        return false;
    }

Guess you like

Origin www.cnblogs.com/lasclocker/p/11410026.html