Leetcode500

leetcode 500 键盘侠

这道题我的思想是,找一个相对应的映射,从而把24个字母都映射到HashMap上,从而便于自己查找。

以下便是代码:

public String[] findWords(String[] words) {

    
    int count=0;
    boolean []pos=new boolean[words.length];
    int index=0;
    for(int i=0;i<words.length;i++){
        if(test(words[i])){
            pos[i]=true;
            count++;
        }
    }
    String[]ans=new String[count];
    for(int i=0;i<pos.length;i++){
        if(pos[i]){
            ans[index++]=words[i];
        }
    }
    return ans;

}
public boolean test(String str){
    java.util.HashMap<Character,Integer>map;
    map=new java.util.HashMap<>();
    String []word={"qwertyuiopQWERTYUIOP","asdfghjklASDFGHJKL","zxcvbnmZXCVBNM"};
    for(int i=0;i<word.length;i++){
        for(int j=0;j<word[i].length();j++){
            map.put(word[i].charAt(j),i+1);
        }
    }
    if(str==null||str.length()<0)
        return false;
    int index=map.get(str.charAt(0));
    for(int i=1;i<str.length();i++){
        if(index!=map.get(str.charAt(i)))
            return false;
    }
    return true;
}

猜你喜欢

转载自www.cnblogs.com/Yunrui-blogs/p/12303958.html
今日推荐