Java low level solution with explanation


  • 0
    D
    public class Solution {
        public String[] findWords(String[] words) 
        {
            if (words == null || words.length == 0) { return new String[0]; }
            
            String[] rows = {"qwertyuiop","asdfghjkl","zxcvbnm"};
            
            List<String> res = new ArrayList<>();
            
            // traverse words array
            for (int i = 0; i < words.length; i++)
            {
                // to lower case
                String w = words[i].toLowerCase();
                
                // traverse row in rows array, only 3 rows
                for (int j = 0; j < rows.length; j++)
                {
                    // find which row the word belongs to by check the first character
                    if (rows[j].contains(w.substring(0, 1)))
                    {
                        int k = 1;
                        for (; k < w.length(); k++)
                        {
                            // if one of the rest character does not in this row, break
                            if (!rows[j].contains(w.substring(k, k + 1))) { break; }
                        }
                        // add word into list
                        if (k == w.length()) { res.add(words[i]); }
                    }
                }
            }
            
            // to String array
            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.