Leetcode Word Pattern

来源:互联网 发布:哪个搜索软件好 编辑:程序博客网 时间:2024/04/26 00:42

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.

Difficulty: Easy


Solution: HashMap


public class Solution {    public boolean wordPattern(String pattern, String str) {        HashMap<String, Character> map = new HashMap<String, Character>();        int index = 0, i = 0;        for(i = 0; i < pattern.length(); i++){            int start = index;            if(index == str.length())                break;            while(index < str.length() && str.charAt(index) != ' '){                index++;            }            String temp = str.substring(start, index);            if(!map.containsKey(temp)){                if(map.containsValue(pattern.charAt(i)))                    return false;                map.put(temp, pattern.charAt(i));            }            else{                if(map.get(temp) != pattern.charAt(i)){                    return false;                }            }            if(index < str.length() && str.charAt(index) == ' ')                index++;        }        if(i != pattern.length() || index!=str.length())            return false;        return true;    }}


0 0