Java solution. Please help me to improve runtime.


  • 0
    Y
    public class Solution {
        public String[] findWords(String[] words) {
            ArrayList<String> output = new ArrayList<String>();
            String temp = " ";
            for(int i = 0; i < words.length; i++){
                temp = words[i];
                if(isOneRow(temp) == true){
                    output.add(temp);
                    temp = " ";
                }
                else{
                    temp = " ";
                }
            }
            String[] finalArray = new String[output.size()];
            finalArray = output.toArray(finalArray);
            return finalArray;
        }
        
        public boolean isOneRow(String word){
            String[] firstRow = {"q","Q","w","W","e","E","r","R","t","T","y","Y","u","U","i","I","o","O","p","P"};
            String[] secondRow = {"a","A","s","S","d","D","f","F","g","G","h","H","j","J","k","K","l","L"};
            String[] thirdRow = {"z","Z","x","X","c","C","v","V","b","B","n","N","m","M"};
            int countFirst = 0;
            int countSecond = 0;
            int countThird = 0;
    
            for (int i = 0; i < word.length(); i++){
                if(Arrays.asList(firstRow).contains(String.valueOf(word.charAt(i))) == true){
                    countFirst = countFirst+1;
                }
                
                else if(Arrays.asList(secondRow).contains(String.valueOf(word.charAt(i))) == true){
                    countSecond = countSecond+1;
                }
                
                else if(Arrays.asList(thirdRow).contains(String.valueOf(word.charAt(i))) == true){
                    countThird = countThird +1;
                }
            }
            
            if(countFirst == word.length() || countSecond == word.length() || countThird == word.length()){
                return true;
            }
            else{
                return false;
            }
        }
    }
    

    Any advice how to improve the runtime?


Log in to reply
 

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