500. Keyboard Row
来源:互联网 发布:java 写一句话木马 编辑:程序博客网 时间:2024/06/05 14:48
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:
- You may use one character in the keyboard more than once.
- You may assume the input string will only contain letters of alphabet.
题意:
判断一个单词的每一个字母是否都来自键盘上的同一行,是的话就放在最终结果的数组中
算法思路:
1.首先用3个字符串数组存放三行的字母
2.然后将三行的字母放到map中,对map设置不同的行设置不同的值
3.取每个单词的首字母进行判断,如果在map中取出的值不相等,flag=0,如果都满足在数组集合中添加这个单词
4.将数组list转化为数组
注意:在取每个单词的字母时,取出的是char类型的,直接get键值拿到的是NULL,所以在前面加上“”用来匹配字符串
代码实现
package easy;import java.util.ArrayList;import java.util.HashMap;public class KeyboardRow {public static String[] findWords(String[] words) { String[] row1 = {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"}; String[] row2 = {"a", "s", "d", "f", "g", "h", "j", "k", "l"}; String[] row3 = {"z", "x", "c", "v", "b", "n", "m"}; HashMap hashMap = new HashMap(); ArrayList list = new ArrayList(); //添加第一行 for(int i=0; i<row1.length; i++){ hashMap.put(row1[i], 1); } //添加第二行 for(int i=0; i<row2.length; i++){ hashMap.put(row2[i], 2); } //添加第三行 for(int i=0; i<row3.length; i++){ hashMap.put(row3[i], 3); } for(int i=0; i<words.length; i++){//遍历每一个单词 boolean flag = true; for(int j=0; j<words[i].length(); j++){ if(hashMap.get("" + words[i].toLowerCase().charAt(0)) != hashMap.get("" + words[i].toLowerCase().charAt(j))){ flag = false; break; } } if (flag){ list.add(words[i]); } } String[] result = new String[list.size()]; return (String[])list.toArray(result); }public static void main(String[] args){String[] words = {"Hello", "Alaska", "Dad", "Peace"};String[] result = findWords(words);for(int i=0; i<result.length; i++){System.out.println(result[i]);}}}
阅读全文
0 0
- Leetcode-500. Keyboard Row
- 【Leetcode】500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row
- 【LeetCode】500. Keyboard Row
- 500. Keyboard Row
- LeetCode 500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row
- LeetCode 500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row (E)
- 500. Keyboard Row
- 500. Keyboard Row
- leetcode 500. Keyboard Row
- 500. Keyboard Row
- [LeetCode]500. Keyboard Row
- 500. Keyboard Row
- Contect、SharedPreferences及Intent学习小记
- 树的重心
- 过去10年来,SEO技术有多大变化?
- java中数据结构时间复杂度
- 数据库事务
- 500. Keyboard Row
- Qt基础 07_单选框、复选框及实例
- ffmpeg在window下编译32位
- jQuery ajax
- 分布式消息kafka
- ASP.NET MVC IOC 之AutoFac攻略
- 如何更改vue项目运行的端口号
- java获取当前路径的几种方法
- 阿里云centos服务器基本构建(服务器的探索之路)