【LeetCode】Keyboard Row 解题报告

来源:互联网 发布:淘宝一单刷几百件 编辑:程序博客网 时间:2024/05/16 00:33

【LeetCode】Keyboard Row 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/keyboard-row/#/description

题目描述:

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”]

Ways

暴力解决了。分别把三行弄在三个数组里,对于每个单词每个字母都去循环,数在三行中的个数分别多少。如果这个单词能在一张中打出来完,那么说明由某一行的个数为1,其他行都为0.

注意字符串数组的写法。

public class Solution {    public String[] findWords(String[] words) {        char []arr1 = new char[]{'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P'};        char []arr2 = new char[]{'a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L'};        char []arr3 = new char[]{'z','x','c','v','b','n','m','Z','X','C','V','B','N','M'};        List<String> ans = new ArrayList<String>();        for(String word: words){            int count1 = 0, count2 = 0, count3 = 0;            for(int i =0; i < word.length(); i++){                for(int j =0; j < arr1.length; j++){                    if(word.charAt(i) == arr1[j]){                        count1++;                    }                }                for(int j =0; j < arr2.length; j++){                    if(word.charAt(i) == arr2[j]){                        count2++;                    }                }                for(int j =0; j < arr3.length; j++){                    if(word.charAt(i) == arr3[j]){                        count3++;                    }                }            }            if((count1 != 0 && count2 == 0 && count3 == 0)                ||(count1 == 0 && count2 != 0 && count3 == 0)                ||(count1 == 0 && count2 == 0 && count3 != 0)){                    ans.add(word);            }        }        String []answer = new String[ans.size()];        for(int i =0; i < ans.size(); i ++){            answer[i] = ans.get(i);        }        return answer;    }}

Date

2017 年 4 月 2 日

0 0
原创粉丝点击