Very Simple Java Solution - 3 ms


  • 0
    D

    It's really easy and intuitive.

    public String[] findWords(String[] words) {
            String row1 = "qwertyuiopQWERTYUIOP";
            String row2 = "asdfghjklASDFGHJKL";
            String row3 = "zxcvbnmZXCVBNM";
            List<String> res = new ArrayList<String>();
    
            for(String word: words) {
                char[] wordArray = word.toCharArray();
                int inRow = 0;
    
                for(char ch: wordArray) {
                    if(row1.indexOf(ch) != -1 && (inRow == 0 || inRow == 1))
                        inRow = 1;
                    else if(row2.indexOf(ch) != -1 && (inRow == 0 || inRow == 2))
                        inRow = 2;
                    else if(row3.indexOf(ch) != -1 && (inRow == 0 || inRow == 3))
                        inRow = 3;
                    else    {
                        inRow = -1;
                        break;
                    }
                }
                if(inRow != -1) {
                    res.add(word);
                }
            }
            return res.toArray(new String[0]);
        }
    

Log in to reply
 

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