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.

一刷
题解:本来以为用character->string会很容易求解,但是怎么解决多个character对应同一个string的问题呢。再加个set

class Solution {
    public boolean wordPattern(String pattern, String str) {
        Map map = new HashMap<>();
        Set set = new HashSet<>();
        str = str.trim();
        String[] strings = str.split(" ");
        if(pattern.length()!=strings.length) return false;
        for(int i=0; i

方法2:
map: String->Integer(index)
如果pattern和string对应的index不同,false
且注意,map.put的返回值为value. 如果map在此时更新,那么返回的是原先的value, 并更新为现在的value; 即第一次更新返回的是null.
于是,if(map.put(String.valueOf(pattern.charAt(i))) !=map.put(strs[i], i)) return false;;可以使它们满足一一对应的关系。

如何解决input:

 "abc"
"b c a"

这样会造成string和pattern的conflict
于是在构造map的时候不制定map的类型,可以同时用character和string作为key

class Solution {
    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

你可能感兴趣的:(290. Word Pattern)