JAVA 3 MS TIME AND THOROUGH EXPLAINATION!!


  • 0
    J
    import java.util.ArrayList;
    public class Solution {
        
        // define keyboard rows
        private final String row0 = "QWERTYUIOP";
        private final String row1 = "ASDFGHJKL";
        private final String row2 = "ZXCVBNM";
        
        public String[] findWords(String[] words) {
            
            // use ArrayList to add the matching words (because we don't know the number of matching words ahead of time).
            ArrayList<String> matchingWords = new ArrayList<String>();
            
            // rowActive is for checking if the next character in the word goes to another keyboard row.
            boolean[] rowActive = new boolean[3];
            
            for(int i = 0; i < words.length; i++){
                // first loop iterates through the words.
                
                // reset the rowActive booleans for the new word
                rowActive[0] = false;
                rowActive[1] = false;
                rowActive[2] = false;
                
                for(int k = 0; k < words[i].length(); k++){
                    // second loop iterates through each words characters.
                    
                    // grab a character at k position, set it upper case and assign it to a string.
                    String tempChar = String.valueOf(Character.toUpperCase(words[i].charAt(k)));
    
                    // check to see which row tempChar string is contained in.
                    // if on later iterations, tempChar goes to a different row, 
                    // break out of the 2nd loop(the word won't be added).
                    if(row0.contains(tempChar)){
                        if(rowActive[1] || rowActive[2]) break;
                        rowActive[0] = true;
                    }
                    if(row1.contains(tempChar)){
                        if(rowActive[0] || rowActive[2]) break;
                        rowActive[1] = true;
                    }
                    if(row2.contains(tempChar)){
                        if(rowActive[0] || rowActive[1]) break;
                        rowActive[2] = true;
                    }
                    
                    // if all characters are iterated through, meaning the words characters stayed in one row,
                    // add that word to our ArrayList of strings.
                    if(k == words[i].length() - 1){
                        matchingWords.add(words[i]);
                    }
                }
                
            }
            
            // convert the ArrayList<String> to type String[] and return it.
            String[] returningType = new String[matchingWords.size()];
            return matchingWords.toArray(returningType);
            
        }
    }
    

Log in to reply
 

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