290 Word Pattern

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:

  • pattern = "abba", str = "dog cat cat dog" should return true.
  • pattern = "abba", str = "dog cat cat fish" should return false.
  • pattern = "aaaa", str = "dog cat cat dog" should return false.
  • 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.

分析& 代码

哈哈这题算是我splunk面试的题目了

可以建两个map,一个正向记录map和反向revMap

什么长度不同的废话不说了,核心逻辑是:

如果map里面没有patternLetter

    那么如果revMap有word[i],返回false
    不然把这一组正反加入两个map
  否则

    如果map对应的word和当前不和 || revMap没有当前word || revMap对应pattern不是当前pattern
      返回false
  返回true

代码:

public boolean wordPattern(String pattern, String str) {
    String[] words = str.split(" ");
    if (words.length != pattern.length())
        return false;
    Map index = new HashMap();
    for (Integer i=0; i<words.length; ++i)
        if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
            return false;
    return true;
}

但是呢

大家都讨厌两个map,用一个map也可以做,只要知道有一个containsValue()函数就可以了,好像是在没啥要解释的

如果已经有的话,就比较一下存的和现在一不一样

如果没有的话,就看下现在的word有没有在value里

public boolean wordPattern(String pattern, String str) {
    if(pattern == null || str == null) {
        return false;
    }
    String[] words = str.split(" ");
    if(words.length != pattern.length()) {
        return false;
    }
    Map<Character, String> map = new HashMap<>();
    for(int i = 0; i < pattern.length(); i++) {
        char c = pattern.charAt(i);
        if(map.containsKey(c)) {
            if(!map.get(c).equals(words[i])) {
                return false;
            }
        } else {
            if(map.containsValue(words[i])) {
                return false;
            }
            map.put(c, words[i]);
        }
    }
    return true;
}

Steven大神依旧有神奇的做法

public boolean wordPattern(String pattern, String str) {
    String[] words = str.split(" ");
    if (words.length != pattern.length())
        return false;
    Map index = new HashMap();
    for (Integer i=0; i<words.length; ++i)
        if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
            return false;
    return true;
}

其实我觉得这种做法不是那么好啦,因为map都没有说明类型,虽然都是Object类型,但是感觉不是很好呢……

这里要说的意思是,发现了map函数的神奇特质

就是map.put(),如果第二次put进同样的key不同value,返回的值是被挤掉的那个value!不然就是null

所以大神的代码的意思是如果下一次发现了一对Pattern+word,他们上次出现的位置应该是一样的。就是现在放入的这一对,如果在map中已经存在,那么上次放入的也应该是同一对

results matching ""

    No results matching ""