Easy understand though long java code


  • 0
    N

    ...
    public class Solution {
    public String[] findWords(String[] words) {
    HashSet<Character> hs1 = new HashSet<Character>();
    ArrayList<String> list = new ArrayList<String>();
    hs1.add('q');
    hs1.add('w');
    hs1.add('e');
    hs1.add('r');
    hs1.add('t');
    hs1.add('y');
    hs1.add('u');
    hs1.add('i');
    hs1.add('o');
    hs1.add('p');
    HashSet<Character> hs2 = new HashSet<Character>();
    hs2.add('a');
    hs2.add('s');
    hs2.add('d');
    hs2.add('f');
    hs2.add('g');
    hs2.add('h');
    hs2.add('j');
    hs2.add('k');
    hs2.add('l');

    	HashSet<Character> hs3 = new HashSet<Character>();
    	hs3.add('z');
    	hs3.add('x');
    	hs3.add('c');
    	hs3.add('v');
    	hs3.add('b');
    	hs3.add('n');
    	hs3.add('m');
    
    	for (int i = 0; i < words.length; i++) {
    		String originalWords = words[i];
    		words[i] = words[i].toLowerCase();
    		HashSet<Character> record = new HashSet<Character>();
    
    		// check hs1
    		if (hs1.contains(words[i].charAt(0))) {
    			record.add('y');
    			for (int j = 1; j < words[i].length(); j++) {
    				if (!hs1.contains(words[i].charAt(j))) {
    					record.add('n');
    				} else {
    					record.add('y');
    				}
    			}
    
    			if (!record.contains('n')) {
    				list.add(originalWords);
    			} 
    		}
    
    		// check hs2
    		if (hs2.contains(words[i].charAt(0))) {
    			record.add('y');
    			for (int j = 1; j < words[i].length(); j++) {
    				if (!hs2.contains(words[i].charAt(j))) {
    					record.add('n');
    				} else {
    					record.add('y');
    				}
    			}
    
    			if (!record.contains('n')) {
    				list.add(originalWords);
    			}
    		}
    
    		// check hs3
    		if (hs3.contains(words[i].charAt(0))) {
    			record.add('y');
    			for (int j = 1; j < words[i].length(); j++) {
    				if (!hs3.contains(words[i].charAt(j))) {
    					record.add('n');
    				} else {
    					record.add('y');
    				}
    			}
    
    			if (!record.contains('n')) {
    				list.add(originalWords);
    			} 
    		}
    	}
    
    	String[] result = new String[list.size()];
    	for (int i = 0; i < list.size(); i++) {
    		result[i] = list.get(i);
    	}
    
    	return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.