java 290.单词模式(#two HashMap).java Posted 2021-05-08
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 290.单词模式(#two HashMap).java相关的知识,希望对你有一定的参考价值。
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (Integer i=0; i<words.length; ++i)
if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
return false;
return true;
}
/*
Put Method Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)*/
public class Solution {
public boolean wordPattern(String pattern, String str) {
if(pattern == null || pattern.length() == 0) return false;
if(str == null || str.length() == 0) return false;
String[] arr = str.split(" ");
if(pattern.length() != arr.length) {
return false;
}
HashMap<Character, String> map = new HashMap<>();
for(int i =0; i < pattern.length(); i ++) {
char ch = pattern.charAt(i);
String temp = arr[i];
if(map.containsKey(ch)) {
if(!map.get(ch).equals(temp)) {
return false;
}
} else {
map.put(ch, temp);
}
}
HashSet<String> vals = new HashSet<>();
vals.addAll(map.values());
return vals.size() == map.values().size();
}
}
public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] strs = str.split(" ");
if (strs.length != pattern.length()) return false;
Map<Character, String> map1 = new HashMap<>();
Map<String, Character> map2 = new HashMap<>();
for(int i = 0; i < pattern.length(); i++) {
char p = pattern.charAt(i);
String s = strs[i];
if ((map1.containsKey(p) && !map1.get(p).equals(s)) || (map2.containsKey(s) && map2.get(s) != p)) {
return false;
}
map1.put(p,s);
map2.put(s,p);
}
return true;
}
}
以上是关于java 290.单词模式(#two HashMap).java的主要内容,如果未能解决你的问题,请参考以下文章
java 290.单词模式(#two HashMap).java
java 290.单词模式(#two HashMap).java
java 290.单词模式(#two HashMap).java
java 290.单词模式(#two HashMap).java
Leetcode 290. 单词模式
[LeetCode] 290. Word Pattern 单词模式