zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    poj 2528 Mayor's posters (线段树+离散化)
    poj 1201 Intervals (差分约束)
    hdu 4109 Instrction Arrangement (差分约束)
    poj 1195 Mobile phones (二维 树状数组)
    poj 2983 Is the Information Reliable? (差分约束)
    树状数组 讲解
    poj 2828 Buy Tickets (线段树)
    hdu 1166 敌兵布阵 (树状数组)
    Ubuntu网络配置
    Button控制窗体变量(开关控制灯的状态)
  • 原文地址:https://www.cnblogs.com/insaneXs/p/6373267.html
Copyright © 2011-2022 走看看