classSolution { publicbooleanwordPattern(String pattern, String str) { Map<String, Character> str2ch = newHashMap<String, Character>(); Map<Character, String> ch2str = newHashMap<Character, String>(); intm= str.length(); inti=0; for (intp=0; p < pattern.length(); ++p) { charch= pattern.charAt(p); if (i >= m) { returnfalse; } intj= i; while (j < m && str.charAt(j) != ' ') { j++; } Stringtmp= str.substring(i, j); if (str2ch.containsKey(tmp) && str2ch.get(tmp) != ch) { returnfalse; } if (ch2str.containsKey(ch) && !tmp.equals(ch2str.get(ch))) { returnfalse; } str2ch.put(tmp, ch); ch2str.put(ch, tmp); i = j + 1; } return i >= m; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcwordPattern(pattern string, s string)bool { word2ch := map[string]byte{} ch2word := map[byte]string{} words := strings.Split(s, " ") iflen(pattern) != len(words) { returnfalse } for i, word := range words { ch := pattern[i] if word2ch[word] > 0 && word2ch[word] != ch || ch2word[ch] != "" && ch2word[ch] != word { returnfalse } word2ch[word] = ch ch2word[ch] = word } returntrue }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var wordPattern = function(pattern, s) { const word2ch = newMap(); const ch2word = newMap(); const words = s.split(' '); if (pattern.length !== words.length) { returnfalse; } for (const [i, word] of words.entries()) { const ch = pattern[i]; if (word2ch.has(word) && word2ch.get(word) != ch || ch2word.has(ch) && ch2word.get(ch) !== word) { returnfalse; } word2ch.set(word, ch); ch2word.set(ch, word); } returntrue; };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defwordPattern(self, pattern: str, s: str) -> bool: word2ch = dict() ch2word = dict() words = s.split() iflen(pattern) != len(words): returnFalse for ch, word inzip(pattern, words): if (word in word2ch and word2ch[word] != ch) or (ch in ch2word and ch2word[ch] != word): returnFalse word2ch[word] = ch ch2word[ch] = word returnTrue