当前位置: 代码迷 >> 综合 >> LeetCode-Java-500. Keyboard Row
  详细解决方案

LeetCode-Java-500. Keyboard Row

热度:30   发布时间:2023-12-16 09:12:18.0

题目

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.American keyboard
row1:qwertyuiop
row2:asdfghjkl
row3:zxcvbnmExample 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.

代码

此题重点是考虑各种各样的情况

class Solution {
    public  String[] findWords(String[] words) {List<Character> row1 = Arrays.asList('q','w','e','r','t','y','u','i','o','p');List<Character> row2 = Arrays.asList('a','s','d','f','g','h','j','k','l');List<Character> row3 = Arrays.asList('z','x','c','v','b','n','m');int sum = 0;int len = words.length;for(int i =0;i<len;i++){String temp = words[i];int lenb = temp.length();char A = temp.charAt(0);int bu = -32;if(A<92){bu = 32;}char B = (char) (A+bu);if(       ((row1.contains(A)||row1.contains(B))&&fun(row1,temp))||((row2.contains(A)||row2.contains(B))&&fun(row2,temp))||((row3.contains(A)||row3.contains(B))&&fun(row3,temp)) ){words[sum++] = temp;}}return Arrays.copyOf(words,sum);}public static boolean fun(List<Character> row,String x){int len = x.length();for(int i=0;i<len;i++){if(!row.contains(x.charAt(i))&&!row.contains((char)(x.charAt(i)-32))&&!row.contains((char)(x.charAt(i)+32))){return false;}}return true;}
}
  相关解决方案