Java AC Solution, Easy to understand beats 95.67% in 2ms


  • 3
    V
    public class Solution 
    {
        String[] rows = new String[]{"QWERTYUIOPqwertyuiop","ASDFGHJKLasdfghjkl","ZXCVBNMzxcvbnm"};
            
        public String[] findWords(String[] words) 
        {
            ArrayList<String> result = new ArrayList<String>();
        
            int currentRow = 0;
            boolean found = true;
            for(String s : words)
            {
                currentRow = getCurrentRow(s.charAt(0));
                found = true;
                for(char c: s.toCharArray())
                {
                    if(rows[currentRow].indexOf(c) == -1)
                    {
                        found = false;
                        break;
                    }
                }
                if(found)
                   result.add(s);
            }
            
            return result.toArray(new String[result.size()]);
        }
        
        private int getCurrentRow(char c)
        {
           for(int rowNumber = 0; rowNumber < 3 ; rowNumber++)
           {
               if (rows[rowNumber].indexOf(c) != -1)
               {
                   return rowNumber;
               }
           }
           return -1;
        }
    }
    

  • 0
    R

    Hard code the keyboard strings in sorted order and binary search for:
    M A X I M U M E F F E C T


Log in to reply
 

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