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.

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

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

    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; } }
     
  • 相关阅读:
    May 1 2017 Week 18 Monday
    April 30 2017 Week 18 Sunday
    April 29 2017 Week 17 Saturday
    April 28 2017 Week 17 Friday
    April 27 2017 Week 17 Thursday
    April 26 2017 Week 17 Wednesday
    【2017-07-04】Qt信号与槽深入理解之一:信号与槽的连接方式
    April 25 2017 Week 17 Tuesday
    April 24 2017 Week 17 Monday
    为什么丑陋的UI界面却能创造良好的用户体验?
  • 原文地址:https://www.cnblogs.com/baichangfu/p/7439678.html
Copyright © 2011-2022 走看看