Java Solution


  • 0

    '''
    public String[] findWords(String[] words) {
    List<String> result = new ArrayList<>();
    String[] strs = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};

    	//put the all characters along with row number into map
    	Map<String, Integer> map = new HashMap<String, Integer>();
    	for(int i=0; i<strs.length; i++){
    		String str = strs[i];
    		
    		for(int j=0; j<str.length(); j++){
    			String key = String.valueOf(str.charAt(j));
    			map.put(key, i);
    		}
    	}
    	
    	for(String word: words){
    	    if (word == null || word.trim().length() == 0) continue;
    	    
    		String fChar = String.valueOf(word.charAt(0)).toLowerCase();
    		int rowNum = map.get(fChar);
    		boolean isInSameRow = true;
    		
    		CHAR_LOOP: for(int i=0; i<word.length(); i++){
    			String key = String.valueOf(word.charAt(i)).toLowerCase();
    			if(rowNum != map.get(key)){
    				isInSameRow = false;
    				break CHAR_LOOP;
    			}
    		}
    		
    		if(isInSameRow) 
    			result.add(word);
    	}
    	
    	String[] arr = new String[result.size()];
    	for(int i=0; i<result.size(); i++)
    		arr[i] = result.get(i);
    	
        return arr;
    }

Log in to reply
 

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