波波老师您好,290我总结一点就是利用map进行一一对应关系,我的方法是分别构建2个hashmap然后分别验证一一对应,但是我在测试的时候发现,在输入一个cat之后,明明这个string就等于map里存着的string,但是它依然判断为false?老师您可以帮我看看为啥么?
我的代码:
import java.util.HashMap;
/**using hashtable
* time complexity:
* space complexity:
* */
public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] words=str.split(" ");
if(pattern.length()!=words.length)
return false;
HashMap<Character,String> map = new HashMap<>();
for(int i=0;i<pattern.length();i++) {
if(map.containsKey(pattern.charAt(i))) {
if(map.get(pattern.charAt(i))!=words[i])
return false;
}
else
map.put(pattern.charAt(i), words[i]);
}
HashMap<String,Character> map1 = new HashMap<>();
for(int i=0;i<words.length;i++) {
if(map1.containsKey(words[i])) {
if(map1.get(words[i])!=pattern.charAt(i))
return false;
}
else
map1.put(words[i], pattern.charAt(i));
}
return true;
}
public static void main(String[] args) {
String pattern="abba";
String str="dog cat cat dog";
System.out.print(new Solution().wordPattern(pattern, str));
}
}