zoukankan      html  css  js  c++  java
  • 500. 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.

    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.

    链接:https://leetcode.com/problems/keyboard-row/#/description

    3/29/2017

    performance 8ms, beat 15%

    注意的问题:

    1. 第3,4,5行的初始化

    2. 第11,12行的建立set。为什么不能采取1中的方法?Character[]和char[]是不能自动转化的。我对Java了解不清,需要仔细研究。

    3. 第6,15行,ArrayList和[]转化

    4. set1.retainAll(set2)是求交集,set1.containsAll(set2)是求s2是否为s1的子集

     1 public class Solution {
     2     public String[] findWords(String[] words) {
     3         Set<Character> s1 = new HashSet<Character>(Arrays.asList('q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'));
     4         Set<Character> s2 = new HashSet<Character>(Arrays.asList('a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'));
     5         Set<Character> s3 = new HashSet<Character>(Arrays.asList('z', 'x', 'c', 'v', 'b', 'n', 'm'));
     6         ArrayList<String> tmp = new ArrayList<String>();
     7 
     8         for (int i = 0; i < words.length; i++) {
     9             Set<Character> s = new HashSet<Character>();
    10             String t = words[i].toLowerCase();
    11             for (int j = 0; j < words[i].length(); j++) 
    12                 s.add(t.charAt(j));
    13             if (s1.containsAll(s) || s2.containsAll(s) || s3.containsAll(s)) tmp.add(words[i]);
    14         }
    15         String[] ret = tmp.toArray(new String[tmp.size()]);
    16         return ret;
    17     }
    18 }

    看别人的算法,基本上如果performance好的话,在循环体里不用containsAll而是自己单独每个character比较。

    更多讨论:

    https://discuss.leetcode.com/category/649/keyboard-row

  • 相关阅读:
    DROP TABLE 恢复【一】
    Recover InnoDB dictionary
    Percona XtraDB Cluster
    主从复制延时判断
    Keepalived+MySQL实现高可用
    Performance Tuning MySQL
    Redis实现异步消息队列与延时队列
    Python多线程中的setDaemon
    Python实现远程控制单片机led状态
    【机器学习】朴素贝叶斯应用实例
  • 原文地址:https://www.cnblogs.com/panini/p/6645172.html
Copyright © 2011-2022 走看看