给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
美式键盘 中:
示例1:
输入:words = ["Hello","Alaska","Dad","Peace"]
输出:["Alaska","Dad"]
示例2:
输入:words = ["omk"]
输出:[]
示例3:
输入:words = ["adsdf","sfd"]
输出:["adsdf","sfd"]
提示:
我们为每一个英文字母标记其对应键盘上的行号,然后检测字符串中所有字符对应的行号是否相同。
代码:
public class Solution {
public string[] 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 = new string[list.Count];
for (int i = 0; i < list.Count; ++i) {
ans[i] = list[i];
}
return ans;
}
}
执行结果
通过
执行用时:152 ms,在所有 C# 提交中击败了49.50%的用户
内存消耗:41.4 MB,在所有 C# 提交中击败了24.90%的用户
思路解析 我们为每一个英文字母标记其对应键盘上的行号,然后检测字符串中所有字符对应的行号是否相同。
代码:
class Solution {
public String[] findWords(String[] words) {
List<String> list = new ArrayList<String>();
String rowIdx = "12210111011122000010020202";
for (String word : words) {
boolean isValid = true;
char idx = rowIdx.charAt(Character.toLowerCase(word.charAt(0)) - 'a');
for (int i = 1; i < word.length(); ++i) {
if (rowIdx.charAt(Character.toLowerCase(word.charAt(i)) - 'a') != idx) {
isValid = false;
break;
}
}
if (isValid) {
list.add(word);
}
}
String[] ans = new String[list.size()];
for (int i = 0; i < list.size(); ++i) {
ans[i] = list.get(i);
}
return ans;
}
}
执行结果
通过
执行用时:0 ms,在所有 Java 提交中击败了100.76%的用户
内存消耗:36.4 MB,在所有 Java 提交中击败了89.40%的用户
C#
和 Java
两种编程语言进行解题