Fast (95%, 2ms) and easy to understand java solution


  • 3
    H
    public class Solution {
                                             // zyxwvutsrqponmlkjihgfedcba
        private static final int ROW1 = 0b00000001010110111100000100010000;
        private static final int ROW2 = 0b00000000000001000000111011101001;
        private static final int ROW3 = 0b00000010101000000011000000000110;
            
        public String[] findWords(String[] words) {
            String [] validWords = new String[words.length];
            int validWordsFound = 0;
            int wordLetterIndexes = 0;
            for (String word: words) {
                wordLetterIndexes = getLetterIndexes(word);
                if ((wordLetterIndexes & ROW1) == wordLetterIndexes
                    || (wordLetterIndexes & ROW2) == wordLetterIndexes
                    || (wordLetterIndexes & ROW3) == wordLetterIndexes) {
                        validWords[validWordsFound++] = word;
                    }
            }
            return Arrays.copyOf(validWords, validWordsFound);
        }
        
        private static final int getLetterIndexes(String word) {
            int letters = 0;
            char c;
            for (int i = 0; i < word.length(); i++) {
                c = word.charAt(i);
                letters |= 1 << ((c < 'a') ? c - 'A' : c - 'a');
            }
            return letters;
        }
    }
    

  • 0
    W

    Thanks for sharing! This solution is really cool!


  • 0
    H

    May you explain it? thanks


Log in to reply
 

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