word break/pattern/ladder

139. Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] f = new boolean[s.length() + 1];
        f[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (f[j] && wordDict.contains(s.substring(j, i))) {
                    f[i] = true;
                    break;
                }
            }
        }
        return f[s.length()];
    }

140. Word Break II

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

public List<String> wordBreak(String s, List<String> wordDict) {
        List<String> res = new ArrayList<>();
        if(s.length() == 0) return res;
        Map<String, List<String>> map = new HashMap<>();
        return helper(s, wordDict, map);
    }
    private List<String> helper(String s, List<String> wordDict, Map<String, List<String>> map) {
        if(map.containsKey(s)) return map.get(s);
        List<String> res = new ArrayList<>();
        if(s.length() == 0) {
            res.add("");
            return res;
        }
        for(String word : wordDict) {
            if(s.startsWith(word)) {
                List<String> temp = helper(s.substring(word.length()), wordDict, map);
                for(String str : temp) {
                    res.add(word + (str.length() == 0 ? "" : " ") + str);
                }
            }
        }
        map.put(s, res);
        return res;
    }

290. Word Pattern

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

public boolean wordPattern(String pattern, String str) {
	Map<Character, String> map = new HashMap<Character,String>();
	String[] tokens = str.split(" ");
        int s_len = tokens.length;          // value
        int p_len = pattern.length();  // key
        if (s_len != p_len) return false;
        
        for (int i = 0; i < p_len; i++) {
            char k = pattern.charAt(i);
            String v = tokens[i];
            if (!map.containsKey(k)) {
                if (map.containsValue(v)) return false;
                map.put(k, v);
            }
            else {
                if (!map.get(k).equals(v)) return false;
            }
        } 
        return true;
    }

291. Word Pattern II

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty substring in str.

Examples:

  1. pattern = "abab", str = "redblueredblue" should return true.
  2. pattern = "aaaa", str = "asdasdasdasd" should return true.
  3. pattern = "aabb", str = "xyzabcxzyabc" should return false.

Notes:
You may assume both pattern and str contains only lowercase letters.

用 map 来储存 pattern 中的字母str中的字符串的映射。判断 对错 的条件是 p 和 s 是否 同时到达 pattern 和 str 的最后一位。

	if (map[c - 'a'] != null) {
            int len = map[c - 'a'].length();
            for (int i = 0; i < len; i++) {
                if (s + i >= str.length() || str.charAt(s + i) != map[c - 'a'].charAt(i)) return false;
            }
            return helper(pattern, p + 1, str, s + len, map, set);
        }



public boolean wordPatternMatch(String pattern, String str) {
        String[] map = new String[26];
        return helper(pattern, 0, str, 0, map, new HashSet<>());
    }
    
    private boolean helper(String pattern, int p, String str, int s, String[] map, HashSet<String> set) {
        if (p == pattern.length() && s == str.length()) return true; 
        if (p == pattern.length() || s == str.length()) return false;
        
        char c = pattern.charAt(p);
        if (map[c - 'a'] != null) {
            int len = map[c - 'a'].length();
            for (int i = 0; i < len; i++) {
                if (s + i >= str.length() || str.charAt(s + i) != map[c - 'a'].charAt(i)) return false;
            }
            return helper(pattern, p + 1, str, s + len, map, set);
        }
        else {
            for (int i = s; i < str.length(); i++) {
                String tmp = str.substring(s, i + 1);
                if (set.add(tmp)) {
                    map[c - 'a'] = tmp;
                    if (helper(pattern, p + 1, str, i + 1, map, set)) return true;
                    map[c - 'a'] = null;
                    set.remove(tmp);
                }
            }
        }
        return false;
    }


79. Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]
word  =  "ABCCED" , -> returns  true ,
word  =  "SEE" , -> returns  true ,
word  =  "ABCB" , -> returns  false .

public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || board[0].length == 0) return false;
        int row = board.length, col = board[0].length;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (word.charAt(0) != board[i][j]) continue;
                if (exist(board, i, j, word, 0)) return true;
            }
        }
        return false;
    }

    private boolean exist(char[][] board, int x, int y, String word, int start) {
        if(start == word.length()) return true;
        if(x < 0 || x >= board.length || y < 0 || y >= board[0].length || board[x][y] != word.charAt(start) || board[x][y] == '#') return false;
        if (board[x][y] == word.charAt(start)) {
            char c = board[x][y];
            board[x][y] = '#';
            boolean res = exist(board, x + 1, y, word, start + 1) || 
                          exist(board, x - 1, y, word, start + 1) ||
                          exist(board, x, y + 1, word, start + 1) || 
                          exist(board, x, y - 1, word, start + 1);
            board[x][y] = c;
            return res;
        }
        return false;
    }

212. Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
Return  ["eat","oath"] .

Note:
You may assume that all inputs are consist of lowercase letters a-z.

public List<String> findWords(char[][] board, String[] words) {
        List<String> res = new ArrayList<>();
        TrieNode root = buildTrie(words);
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                dfs (board, i, j, root, res);
            }
        }
        return res;
    }

    public void dfs(char[][] board, int i, int j, TrieNode p, List<String> res) {
        char c = board[i][j];
        if (c == '#' || p.next[c - 'a'] == null) return;
        p = p.next[c - 'a'];
        if (p.word != null) {   // found one
            res.add(p.word);
            p.word = null;     // de-duplicate
        }
        board[i][j] = '#';
        if (i > 0) dfs(board, i - 1, j ,p, res); 
        if (j > 0) dfs(board, i, j - 1, p, res);
        if (i < board.length - 1) dfs(board, i + 1, j, p, res); 
        if (j < board[0].length - 1) dfs(board, i, j + 1, p, res); 
        board[i][j] = c;
    }

    public TrieNode buildTrie(String[] words) {
        TrieNode root = new TrieNode();
        for (String w : words) {
            TrieNode p = root;
            for (char c : w.toCharArray()) {
                int i = c - 'a';
                if (p.next[i] == null) p.next[i] = new TrieNode();
                p = p.next[i];
           }
           p.word = w;
        }
        return root;
    }

    class TrieNode {
        TrieNode[] next;
        String word;
        public TrieNode() {
            this.next = new TrieNode[26];
        }
    }

127. Word Ladder

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not thesame.
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        if (wordList.size() == 0) return 0;   
        Set<String> dict = new HashSet<>(wordList);
        LinkedList<String> wordQueue = new LinkedList<String>();  
        LinkedList<Integer> distanceQueue = new LinkedList<Integer>();  
   
        wordQueue.add(beginWord);  
        distanceQueue.add(1);  

        while(!wordQueue.isEmpty()){  
            String currWord = wordQueue.pop();  
            Integer currDistance = distanceQueue.pop();
             if(currWord.equals(endWord)){  
                return currDistance;  
            }  
            for(int i=0; i<currWord.length(); i++){  
                char[] currCharArr = currWord.toCharArray();  
                for(char c='a'; c<='z'; c++){  
                    currCharArr[i] = c;  
   
                    String newWord = new String(currCharArr);  
                    if(dict.contains(newWord)){  
                        wordQueue.add(newWord);  
                        distanceQueue.add(currDistance+1);  
                        dict.remove(newWord);  
                    }  
                }  
            }  
        }  
        return 0;  
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值