本文共 1563 字,大约阅读时间需要 5 分钟。
Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.
Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]
beats 50%,循环较多
public class Solution { public String[] findWords(String[] words) { //将键盘的三行字母串存到数组里 String[] keyboardRows = { "qwertyuiop", "asdfghjkl", "zxcvbnm"}; //创建一个list存放符合要求的单词 Listlist = new ArrayList (); //对words循环,取出符合要求的单词 for(int i = 0; i < words.length; i++) { //预设当前单词所在行,-1 int line = -1; //将当前单词转化为小写 String lowWords = words[i].toLowerCase(); //对单词每个字母循环判断 for(int j = 0; j < lowWords.length(); j++) { //若是第一个字母,得到其所在行以供后面字符的判断 if(j == 0) { for(int k = 0; k < 3; k++) { if(-1 != keyboardRows[k].indexOf(lowWords.charAt(0))) { line = k; break; } } } else { //将每个字母与第一行字母所在行比较,若不一致则将单词所在行设为-1 if(keyboardRows[line].indexOf(lowWords.charAt(j)) == -1) { line = -1; break; } } } //如果所在行不是-1,说明单词字母在同一行 if(line != -1) list.add(words[i]); } //将list转化为字符串数组return String[] results = new String[list.size()]; return list.toArray(results); }}
转载地址:http://uijgj.baihongyu.com/