simple java solution


  • 0
    2
    public class Solution {
        
        private int[] rows;
        
        public Solution() {
            rows = new int[256];
            String[] s = {"qwertyuiopQWERTYUIOP", "asdfghjklASDFGHJKL", "zxcvbnmZXCVBNM"};
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < s[i].length(); j++) {
                    rows[s[i].charAt(j)] = i;
                }
            }
        }
        
        public String[] findWords(String[] words) {
            ArrayList<Integer> idx = new ArrayList<Integer>();
            for (int i = 0; i < words.length; i++) {
                if (isOneRow(words[i])) {
                    idx.add(i);
                }
            }
            String[] ret = new String[idx.size()];
            for (int i = 0; i < idx.size(); i++) {
                ret[i] = words[idx.get(i)];
            }
            return ret;
        }
        
        private boolean isOneRow(String s) {
            for (int i = 1; i < s.length(); i++) {
                if (rows[s.charAt(i)] != rows[s.charAt(0)]) {
                    return false;
                }
            }
            return true;
        }
    }
    
    

Log in to reply
 

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