1. 程式人生 > >Leetcode#500. Keyboard Row(鍵盤行)

Leetcode#500. Keyboard Row(鍵盤行)

假設 分享圖片 ring str return rac 分享 import ati

題目描述

給定一個單詞列表,只返回可以使用在鍵盤同一行的字母打印出來的單詞。鍵盤如下圖所示。

技術分享圖片

示例1:

輸入: ["Hello", "Alaska", "Dad", "Peace"]
輸出: ["Alaska", "Dad"]

註意:

  1. 你可以重復使用鍵盤上同一字符。
  2. 你可以假設輸入的字符串將只包含字母。

思路

把鍵盤中的字母和其所在行數放到map中,然後比較一個字符串中是否都來自一行。

代碼實現

package HashTable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 500. Keyboard Row(鍵盤行)
 * 給定一個單詞列表,只返回可以使用在鍵盤同一行的字母打印出來的單詞。
 */
public class Solution500 {
    public static void main(String[] args) {
        Solution500 solution500 = new Solution500();
        String[] words = {"Hello", "Alaska", "Dad", "Peace"};
        solution500.findWords(words);
    }

    /**
     * 把鍵盤中的字母和其所在行數放到map中
     *
     * @param words
     * @return
     */
    public String[] findWords(String[] words) {
        String[] keyboard = {"QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"};
        List<String> res = new ArrayList<>();
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < keyboard.length; i++) {
            for (char c : keyboard[i].toCharArray()) {
                map.put(c, i);
            }
        }
        int index;
        for (String word :
                words) {
            index = map.get(word.toUpperCase().toCharArray()[0]);
            for (char c :
                    word.toUpperCase().toCharArray()) {
                if (map.get(c) != index) {
                    index = -1;
                    break;
                }
            }
            if (index != -1) {
                res.add(word);
            }
        }
        return res.toArray(new String[res.size()]);
    }
}

Leetcode#500. Keyboard Row(鍵盤行)