您的位置:首页 > 其它

LeetCode:Word Pattern

2016-02-02 20:21 417 查看
problem:

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.

Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Solution:

public class Solution {
public boolean wordPattern(String pattern, String str) {
if (pattern.isEmpty() || str.isEmpty()) {
return false;
}

String[] s = str.split(" ");
if (s.length != pattern.length()) {
return false;
}

HashMap<Character, String> hashMap = new HashMap<Character, String>();
for (int i = 0; i < pattern.length(); i++) {
if (hashMap.containsKey(pattern.charAt(i))) {
if (!hashMap.get(pattern.charAt(i)).equals(s[i])) {
return false;
}
} else if (hashMap.containsValue(s[i])) {
return false;
} else {
hashMap.put(pattern.charAt(i), s[i]);
}
}

return true;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: