500. Keyboard Row (Easy)

https://leetcode.com/problems/keyboard-row/

Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

 

 

Example:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

 

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

Solutions

class Solution {

    public String[] findWords(String[] words) {
        if (words == null || words.length == 0) {
            return new String[0];
        }

        Map<String, Integer> rows = new HashMap<>();

        rows.put("q", 0);
        rows.put("w", 0);
        rows.put("e", 0);
        rows.put("r", 0);
        rows.put("t", 0);
        rows.put("y", 0);
        rows.put("u", 0);
        rows.put("i", 0);
        rows.put("o", 0);
        rows.put("p", 0);

        rows.put("a", 1);
        rows.put("s", 1);
        rows.put("d", 1);
        rows.put("f", 1);
        rows.put("g", 1);
        rows.put("h", 1);
        rows.put("j", 1);
        rows.put("k", 1);
        rows.put("l", 1);

        rows.put("z", 2);
        rows.put("x", 2);
        rows.put("c", 2);
        rows.put("v", 2);
        rows.put("b", 2);
        rows.put("n", 2);
        rows.put("m", 2);

        List<String> validWords = new ArrayList<>();
        for (String word : words) {

            int lastRow = -1;
            boolean valid = true;

            for (int i = 0; i < word.length(); i++) {
                String c = word.charAt(i) + "";
                int inRow = rows.get(c.toLowerCase());

                if (i == 0) {
                    lastRow = inRow;
                    continue;
                }

                if (inRow != lastRow) {
                    valid = false;
                }
            }

            if (valid) {
                validWords.add(word);
            }
        }

        String[] ans = new String[validWords.size()];
        validWords.toArray(ans);

        return ans;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-07-03 00:26:46

results matching ""

    No results matching ""