500. Keyboard Row

来源:互联网 发布:手机屏幕直播录像软件 编辑:程序博客网 时间:2024/05/17 01:05

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.


American keyboard


Example 1:

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

Note:

  1. You may use one character in the keyboard more than once.

  1. You may assume the input string will only contain letters of alphabet.
这道题思路比较简单,只是时间复杂度有点高,代码如下:
public String[] findWords(String[] words) {
        ArrayList<String> resultList = new ArrayList<String>();
        // 特殊情况处理
        if(words == null){
            return null;
        }
        
        String[] temp = {"qwertyuiopQWERTYUIOP", "asdfghjklASDFGHJKL", "zxcvbnmZXCVBNM"};
        HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
        
        for(int i = 0; i < temp.length; i++){
            for(int j = 0; j < temp[i].length(); j++){
                hashMap.put(temp[i].charAt(j), i);
            }
        }
        
        for(int i = 0; i < words.length; i++){
            String test = words[i];
            boolean flag = true;
            int index = hashMap.get(test.charAt(0));
            for(int j = 1; j < test.length(); j++){
                if(hashMap.get(test.charAt(j)) != index){
                    flag = false;
                    break;
                }
            }
            
            if(flag){
                resultList.add(test);
            }
        }
        
        String[] result = new String[resultList.size()];
        for(int i = 0; i < result.length; i++){
            result[i] = resultList.get(i);
        }
        return result;
    }

0 0
原创粉丝点击