码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode_500. Keyboard Row

时间:2019-12-30 17:34:40      阅读:47      评论:0      收藏:0      [点我收藏+]

标签:keyboard   ++   letters   ring   eric   one   current   ret   use   

 

500. Keyboard Row

Easy

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:

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.

 

package leetcode.easy;

public class KeyboardRow {
	private static void print_arr(String[] strs) {
		for (String str : strs) {
			System.out.print(str + " ");
		}
		System.out.println();
	}

	private java.util.HashSet<Character> set1 = new java.util.HashSet<Character>();
	private java.util.HashSet<Character> set2 = new java.util.HashSet<Character>();
	private java.util.HashSet<Character> set3 = new java.util.HashSet<Character>();

	public String[] findWords(String[] words) {
		char[] chs1 = { ‘q‘, ‘w‘, ‘e‘, ‘r‘, ‘t‘, ‘y‘, ‘u‘, ‘i‘, ‘o‘, ‘p‘ };
		char[] chs2 = { ‘a‘, ‘s‘, ‘d‘, ‘f‘, ‘g‘, ‘h‘, ‘j‘, ‘k‘, ‘l‘ };
		char[] chs3 = { ‘z‘, ‘x‘, ‘c‘, ‘v‘, ‘b‘, ‘n‘, ‘m‘ };
		boolean flag1 = false;
		boolean flag2 = false;
		boolean flag3 = false;
		java.util.LinkedList<String> result = new java.util.LinkedList<String>();
		int j = 0;
		for (int i = 0; i < chs1.length; i++) {
			set1.add(chs1[i]);
		}
		for (int i = 0; i < chs2.length; i++) {
			set2.add(chs2[i]);
		}
		for (int i = 0; i < chs3.length; i++) {
			set3.add(chs3[i]);
		}
		for (int i = 0; i < words.length; i++) {
			String current = words[i].toLowerCase();
			flag1 = false;
			flag2 = false;
			flag3 = false;
			for (j = 0; j < current.length(); j++) {
				char ch = current.charAt(j);
				if (set1.contains(ch)) {
					flag1 = true;
				} else if (set2.contains(ch)) {
					flag2 = true;
				} else if (set3.contains(ch)) {
					flag3 = true;
				}

				if ((flag1 && !flag2 && !flag3) || (!flag1 && flag2 && !flag3) || (!flag1 && !flag2 && flag3)) {
					continue;
				} else {
					break;
				}
			}
			if (j == current.length()) {
				if ((flag1 && !flag2 && !flag3) || (!flag1 && flag2 && !flag3) || (!flag1 && !flag2 && flag3)) {
					result.add(words[i]);
				}
			}
		}
		return result.toArray(new String[0]);
	}

	@org.junit.Test
	public void test() {
		String[] words = { "Hello", "Alaska", "Dad", "Peace" };
		print_arr(findWords(words));
	}
}

 

LeetCode_500. Keyboard Row

标签:keyboard   ++   letters   ring   eric   one   current   ret   use   

原文地址:https://www.cnblogs.com/denggelin/p/12120570.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!