标签:
题目如下。~
Given a pattern
and a string str
, find if str
follows the same pattern.
Examples:
"abba"
, str = "dog cat cat dog"
should return true."abba"
, str = "dog cat cat fish"
should return false."aaaa"
, str = "dog cat cat dog"
should return false."abba"
, str = "dog dog dog dog"
should return false.
Notes:
pattern
contains only lowercase alphabetical letters, and str
contains words separated by a single space. Each word in str
contains only lowercase alphabetical letters.pattern
and str
do not have leading or trailing spaces.pattern
must 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; } }
标签:
原文地址:http://www.cnblogs.com/orangeme404/p/4865553.html