LeetCode[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.

分析:

用一个HashMap,建立字母和单词的对应关系。

代码:

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

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD All Rights Reserved.

访客数 : | 访问量 :