• 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.

    分析:判断给定的字符串数组中满足在键盘中属于同一行的字符串,并返回该数组集合。注意给定的字符串是大小写混合的。

    思路:将键盘上三行字符分别保存到三个字符串中,然后判断每个字符串是否都属于同一行。具体的看注释:

    class Solution {
        public String[] findWords(String[] words) {
            // 将待对比的数组存入
            String row1 = "qwertyuiop";
            String row2 = "asdfghjkl";
            String row3 = "zxcvbnm";
            // 将符合条件的字符串放入ArrayList,之后转为字符串数组
            ArrayList<String> new_words = new ArrayList<>();
            for (int i = 0; i < words.length; i++) {
                // 标记是否满足条件
                boolean tt = false;
                // 将要检查的字符串转成小写
                String word = words[i].toLowerCase();
                // 标记字符串属于第几行
                int loop = 0;
                for(int j = 0; j < word.length(); j++){
                    char ch = word.charAt(j);
                    if(j==0){
                        // 给初始行赋值
                        if(row1.indexOf(ch)!=-1)
                            loop=1;
                        if(row2.indexOf(ch)!=-1)
                            loop=2;
                        if(row3.indexOf(ch)!=-1)
                            loop=3;
                    }else {
                        // 若存在不同行,则进行标记,不满足条件,为TRUE
                        if(row1.indexOf(ch)!=-1&&loop!=1){
                            tt=true;
                            break;
                        }
                        if(row2.indexOf(ch)!=-1&&loop!=2){
                            tt=true;
                            break;
                        }
                        if(row3.indexOf(ch)!=-1&&loop!=3){
                            tt=true;
                            break;
                        }
                    }
                }
                if (tt) {
                    continue;
                }
                new_words.add(words[i]);
            }
         // 将ArrayList转成字符串数组常用套路 String[] ss
    = new String[new_words.size()]; new_words.toArray(ss); return ss; } }
     
  • 相关阅读:
    FJNU 1151 Fat Brother And Geometry(胖哥与几何)
    FJNU 1157 Fat Brother’s ruozhi magic(胖哥的弱智术)
    FJNU 1159 Fat Brother’s new way(胖哥的新姿势)
    HDU 3549 Flow Problem(最大流)
    HDU 1005 Number Sequence(数列)
    Tickets(基础DP)
    免费馅饼(基础DP)
    Super Jumping! Jumping! Jumping!(基础DP)
    Ignatius and the Princess IV(基础DP)
    Keywords Search(AC自动机)
  • 原文地址:https://www.cnblogs.com/baichangfu/p/7439678.html
Copyright © 2020-2023  润新知