zoukankan      html  css  js  c++  java
  • LeetCode_500. Keyboard Row

    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));
    	}
    }
    
  • 相关阅读:
    [研究笔记]SPFA加上SLF时判负环的条件
    hdu 1290
    hdu 2135
    hdu 1978 how many way
    华中区全国程序设计邀请赛1003
    华中区程序设计大赛1010
    华中程序设计邀请赛1007
    华中区全国设计邀请赛1009
    hdu 2114的补充
    华中区全国设计邀请赛1004
  • 原文地址:https://www.cnblogs.com/denggelin/p/12120570.html
Copyright © 2011-2022 走看看