Leetcode练习 500. Keyboard Row

本文介绍了一种通过美国标准键盘布局来筛选特定单词的方法。利用两种实现方式:一种是使用映射表检查每个单词是否完全由同一键盘行的字母组成;另一种则是采用正则表达式简化流程,提高效率。

摘要生成于 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.


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.

用了一个Map来保存各字符的对应层次信息,之后遍历各字符串进行判断,相对来说效率还是低了点。

之后在网上看到一个用正则式子匹配的,感觉挺不错的

public class Solution {
    public String[] findWords(String[] words) {
        Map<Character, Integer> m = new HashMap<>();
        List<String> a = new ArrayList<>();
        m.put('a', 2);m.put('b', 3);m.put('c', 3);m.put('d', 2);m.put('e', 1);m.put('f', 2);m.put('g', 2);
        m.put('h', 2);m.put('i', 1);m.put('j', 2);m.put('k', 2);m.put('l', 2);m.put('m', 3);m.put('n', 3);
        m.put('o', 1);m.put('p', 1);m.put('q', 1);m.put('r', 1);m.put('s', 2);m.put('t', 1);
        m.put('u', 1);m.put('v', 3);m.put('w', 1);m.put('x', 3);m.put('y', 1);m.put('z', 3);
        for(String s : words)
        {
            int level=m.get(s.toLowerCase().charAt(0));
            int flag=0;
            for(int i=1; i<s.length(); i++)
            {
                if(m.get(s.toLowerCase().charAt(i))!=level)
                {
                    flag = 1;
                    break;
                }
                
            }
            if(flag==0)
            {
                a.add(s);
            }
        }
        String[] ss = new String[a.size()];
        for(int i=0; i<a.size(); i++)
        {
            ss[i] = a.get(i);
        }
        return ss;
        
    }
}

转:

public class Solution {
    public String[] findWords(String[] words) {
		String[] result = null;

		if (words != null) {
			List<String> list = new ArrayList<>();

			String regex = "[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*";
			for (String str : words) {
				if (str.toLowerCase().matches(regex)) {
					list.add(str);
				}
			}

			result = new String[list.size()];
			for (int i = 0; i < list.size(); i++) {
				result[i] = list.get(i);
			}
		}

		return result;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值