[Leetcode] Word Pattern
题目如下。~
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:
patterncontains only lowercase alphabetical letters, andstrcontains words separated by a single space. Each word instrcontains only lowercase alphabetical letters.- Both
patternandstrdo not have leading or trailing spaces. - Each letter in
patternmust map to a word with length that is at least 1.
这题没啥难度。主要是要把逻辑搞清楚。借助hashset来做是最方便的。
至于设置几个hashset,可以用一个也可以用两个,反正看自己的习惯。
代码如下。~
public class Solution {
public boolean wordPattern(String pattern, String str) {
HashSet<Character> chara=new HashSet<>();
HashSet<String> stri=new HashSet<>();
String[] temp=str.split(" ");
if(pattern.length()!=temp.length){
return false;
}
for(int i=0;i<pattern.length();i++){
if(chara.contains(pattern.charAt(i))){
if(!stri.contains(temp[i])){
return false;
}
chara.remove(pattern.charAt(i));
stri.remove(temp[i]);
}else{
if(stri.contains(temp[i])){
return false;
}
chara.add(pattern.charAt(i));
stri.add(temp[i]);
}
}
return true;
}
}
浙公网安备 33010602011771号