您的位置:首页 > 其它

leetcode 290: Word Pattern

2015-10-06 16:10 417 查看

Word Pattern

Total Accepted:
1733
Total Submissions:
6204
Difficulty: Easy

Given a
pattern
and a string
str
, find if
str
follows the same pattern.

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:

Both
pattern
and
str
contains only lowercase alphabetical letters.
Both
pattern
and
str
do not have leading or trailing spaces.
Each word in
str
is separated by a single space.
Each letter in
pattern
must map to a word with length that is at least 1.

Credits:

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

[思路]
char 和 string 一一对应. 建一个map. 同时set里面保存string, 避免重复, 出现多对1的情况.

[CODE]

public class Solution {
public boolean wordPattern(String pattern, String str) {
//input check

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

Map<Character, String> map = new HashMap<>();
Set<String> unique = new HashSet<>();

for(int i=0; i<pattern.length(); i++) {
char c = pattern.charAt(i);
if(map.containsKey(c) ) {
if(!map.get(c).equals(strs[i])) return false;
} else {
if(unique.contains(strs[i])) return false;
map.put(c, strs[i]);
unique.add(strs[i]);
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: