500. Keyboard Row

本文提供了一种解决LeetCode键盘行问题的有效方法,通过分析输入字符串并利用HashSet来检查字符是否位于同一行,最终筛选出符合条件的单词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

转载于:https://www.cnblogs.com/panini/p/6645172.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值