Open hitolz opened 4 years ago
class Solution { public boolean wordPattern(String pattern, String str) { Map<String, Integer> patternMap = new HashMap<>(); StringBuffer patternIndex = new StringBuffer(); int length = pattern.length(); for (int i = 0; i < length; i++) { String s = String.valueOf(pattern.charAt(i)); if (!patternMap.containsKey(s)) { patternMap.put(s, i); patternIndex.append(i); } else { patternIndex.append(patternMap.get(s)); } } String[] strings = str.split(" "); StringBuffer strIndex = new StringBuffer(); Map<String, Integer> strMap = new HashMap<>(); int length1 = strings.length; for (int i = 0; i < length1; i++) { String string = strings[i]; if (!strMap.containsKey(string)) { strMap.put(string, i); strIndex.append(i); } else { strIndex.append(strMap.get(string)); } } if (patternIndex.toString().equals(strIndex.toString())) { return true; } return false; } }