Simple Java Solutions 56 lines of code 2 ms runtime


  • 0
    G

    ...
    public class Solution {
    public String[] findWords(String[] words) {

        char keyboard[][] = {
        					 {'q','w','e','r','t','y','u','i','o','p'},
        					 {'a','s','d','f','g','h','j','k','l'},
        					 {'z','x','c','v','b','n','m'}
        					 };
        List <String> validWords = new ArrayList<String>();
        for(String word: words) {
        	char wordArray[] = word.toLowerCase().toCharArray();
        	boolean validString = true;
       	 	int rowNum = -1;
        	for(int i=0;i<wordArray.length;i++) {
        		
        		//check which row this first character belongs to
        		if(rowNum==-1) {
           		 for(int j=0;j<keyboard.length;j++) {
        			 char rowArray[] = keyboard[j];
        			 
        			  
        			  for (int k=0;k<rowArray.length;k++) {
        				  if(wordArray[i]==rowArray[k]) {
        					  rowNum =  j;
        					  break;
        				  }
        			  }//for
        			  
        			  //once we find the rownum break
        			  if(rowNum!=-1) {
        				  break;
        			  }
        		 } //for       			
        		}
        		else {
           		 String rowString = new String(keyboard[rowNum]);
           		 CharSequence  seq = wordArray[i]+"";
           		 if(!rowString.contains(seq)) {
           			 validString = false;
           			 break;
           		 }
           		 else {
           			 continue;
           		 }       			
        		}        		 
    
        	} //for
        	
        	if(validString) {
        		validWords.add(word);
        	}
        	
        }  //for
        
      
        String[] wordsReturn = validWords.toArray(new String[validWords.size()]);
        return wordsReturn;
      
    }
    

    }
    ...


Log in to reply
 

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