Java solution runtime beats +95% using bit manipulation


  • 0
    M

    '''
    public String[] findWords(String[] words) {
    String firstRow = "qwertyuiop";
    String secondRow = "asdfghjkl";
    String thirdRow = "zxcvbnm";

        int firstRowInt = calRow(firstRow);
        int secondRowInt = calRow(secondRow);
        int thirdRowInt = calRow(thirdRow);
    
        List<String> list = new ArrayList<>();
        for (String word : words) {
            int wordVal = calRow(word);
            if ((((firstRowInt | wordVal) ^ firstRowInt) == 0)
                    || (((secondRowInt | wordVal) ^ secondRowInt) == 0)
                        || (((thirdRowInt | wordVal) ^ thirdRowInt) == 0)) {
                list.add(word);
            }
        }
        String[] strings = new String[list.size()];
        return list.toArray(strings);
    }
    
    private int calRow(String row) {
        int result = 0;
        for (int i = 0; i < row.length(); i++) {
            int val = (int) row.charAt(i);
            if(val > 96){
                result |= 1 << (val - 96);
            } else {
                result |= 1 << (val - 64);
            }
        }
        return result;
    }
    

    '''


Log in to reply
 

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