publicclassSolution { publicstring[] FindWords(string[] words) { IList<string> list = new List<string>(); string rowIdx = "12210111011122000010020202"; foreach (string word in words) { bool isValid = true; char idx = rowIdx[char.ToLower(word[0]) - 'a']; for (int i = 1; i < word.Length; ++i) { if (rowIdx[char.ToLower(word[i]) - 'a'] != idx) { isValid = false; break; } } if (isValid) { list.Add(word); } }
string[] ans = newstring[list.Count]; for (int i = 0; i < list.Count; ++i) { ans[i] = list[i]; } return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9
classSolution: deffindWords(self, words: List[str]) -> List[str]: ans = [] rowIdx = "12210111011122000010020202" for word in words: idx = rowIdx[ord(word[0].lower()) - ord('a')] ifall(rowIdx[ord(ch.lower()) - ord('a')] == idx for ch in word): ans.append(word) return ans
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var findWords = function(words) { const list = []; const rowIdx = "12210111011122000010020202"; for (const word of words) { let isValid = true; const idx = rowIdx[word[0].toLowerCase().charCodeAt() - 'a'.charCodeAt()]; for (let i = 1; i < word.length; ++i) { if (rowIdx[word[i].toLowerCase().charCodeAt() - 'a'.charCodeAt()] !== idx) { isValid = false; break; } } if (isValid) { list.push(word); } } return list; };
[sol1-TypeScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
functionfindWords(words: string[]): string[] { constlist: string[] = []; constrowIdx: string = "12210111011122000010020202"; for (const word of words) { letisValid: boolean = true; constidx: string = rowIdx[word[0].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0)]; for (let i = 1; i < word.length; ++i) { if (rowIdx[word[i].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0)] !== idx) { isValid = false; break; } } if (isValid) { list.push(word); } } return list; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcfindWords(words []string) (ans []string) { const rowIdx = "12210111011122000010020202" next: for _, word := range words { idx := rowIdx[unicode.ToLower(rune(word[0]))-'a'] for _, ch := range word[1:] { if rowIdx[unicode.ToLower(ch)-'a'] != idx { continue next } } ans = append(ans, word) } return }
复杂度分析
时间复杂度:O(L),其中 L 表示 words 中所有字符串的长度之和。
空间复杂度:O(C),其中 C 表示英文字母的个数,在本题中英文字母的个数为 26。注意返回值不计入空间复杂度。