• Keyboard Row


    题意:

    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

    Example 1:

    Input: ["Hello", "Alaska", "Dad", "Peace"]
    Output: ["Alaska", "Dad"]
    

    Note:

    1. You may use one character in the keyboard more than once.
    2. You may assume the input string will only contain letters of alphabet.

    就是让我们判断输入的字符串是否在键盘的同一行上。

    思路很简单,先做记录,再看看有没有什么高明的方法。

    private static char[][] tables = new char[3][];
        static{
            tables[0] = "QWERTYUIOP".toCharArray();
            tables[1] = "ASDFGHJKL".toCharArray();
            tables[2] = "ZXCVBNM".toCharArray();
        }
        public String[] findWords(String[] words) {
            if(words == null){
                return null;
            }
            List<String> list = new ArrayList<String>();
            for(int i=0; i<words.length; i++){
                String str = words[i];
                if(str == null){
                    continue;
                }
                char[] checkChars = str.toUpperCase().toCharArray();
                char[] checkedChars = new char[26];//保存已受检的字符
                //查找目标行
                int target = 0;
                for(;target < tables.length; target++){
                    if(contains(tables[target], checkChars[0])){
                        checkedChars[checkChars[0] - 'A'] = 1;
                        break;
                    }
                }
                char[] targetChar = tables[target];
                //检查剩下的字符
                boolean isValid = true;
                for(int index = 1; index < checkChars.length; index++){
                    char checkChar = checkChars[index];
                    if(checkedChars[checkChar - 'A'] != 0){
                        
                    }else if(!contains(targetChar, checkChar)){
                        isValid = false;
                        break;
                    }
                }
                if(isValid){
                    list.add(str);
                }
            }
            return list.toArray(new String[list.size()]);
        }
        
        private boolean contains(char[] chars, char targetChar){
            for(int i=0; i<chars.length; i++){
                if(chars[i] == targetChar)
                    return true;
            }
            return false;
        }
  • 相关阅读:
    Centos安装步骤
    Charles抓包工具的使用
    Charles抓包问题
    关于Windows系统下端口被占用的问题和task命令
    Selenium3+python自动化016-Selenium Grid
    Selenium3+python自动化016-多线程
    JDBC使用案例
    JDBC基础和使用
    文件下载案例
    ServletContext
  • 原文地址:https://www.cnblogs.com/insaneXs/p/6373267.html
Copyright © 2020-2023  润新知