https://leetcode-cn.com/problems/word-pattern/
使用双向反射
package leetcode;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static boolean wordPattern(String pattern, String s) {
String[] arrayStr = s.split(" ");
char[] arrayChar = pattern.toCharArray();
if(arrayChar.length != arrayStr.length) {
return false;
}
Map map = new HashMap();
Map map2 = new HashMap();
for(int i=0; i<arrayChar.length; i++) {
// System.out.println("11111" + map.get(arrayChar[i]) + ":::" + arrayChar[i] + ":::"+arrayStr[i]);
// System.out.println("11111" + map2.get(arrayStr[i]) + ":::" + arrayChar[i] + ":::"+arrayStr[i]);
if(!map.containsKey(arrayChar[i])) {
// System.out.println("arrayChar[i]:::" + arrayChar[i]);
map.put(arrayChar[i], arrayStr[i]);
}else {
if(!map.get(arrayChar[i]).equals(arrayStr[i])){
// System.out.println("" + map.get(arrayChar[i]) + ":::" + arrayChar[i] + ":::"+arrayStr[i]);
return false;
}
}
if(!map2.containsKey(arrayStr[i])) {
// System.out.println("arrayStr[i]:::" + arrayStr[i]);
map2.put(arrayStr[i], arrayChar[i]);
}else {
// System.out.println("222" + map.get(arrayChar[i]) + ":::" + arrayChar[i] + ":::"+arrayStr[i]);
// System.out.println("2222" + map2.get(arrayStr[i]) + ":::" + arrayChar[i] + ":::"+arrayStr[i]);
if(!map2.get(arrayStr[i]).equals(arrayChar[i])) {
// System.out.println("" + map.get(arrayChar[i]) + ":::" + arrayChar[i] + ":::"+arrayStr[i]);
return false;
}
}
}
return true;
}
public static void main(String[] args) {
System.out.println("" + wordPattern("abba", "dog cat cat fish"));
}
}