1. 程式人生 > >Java/500. Keyboard Row 鍵盤行

Java/500. Keyboard Row 鍵盤行

題目

程式碼部分一(2ms 99.4%)

class Solution {
    List<String> list = new ArrayList();
    public String[] findWords(String[] words) {
        String frist = "QWERTYUIOPqwertyuiop";
        String second = "ASDFGHJKLasdfghjkl";
        String third = "ZXCVBNMzxcvbnm";
        
        for(String temp : words){                          //遍歷String[]
            if(frist.indexOf(temp.charAt(0)) != -1)
               isNeed(frist, temp);
            else if(second.indexOf(temp.charAt(0)) != -1)
                    isNeed(second, temp);
            else if(third.indexOf(temp.charAt(0)) != -1)
                    isNeed(third, temp);
        }
        String[] res = list.toArray(new String[list.size()]);
        return res;

    }
    public void isNeed(String str, String temp){           //判斷該單詞是否符合
        int len = temp.length();
        for(int i = 0; i < len; i++){
            if(str.indexOf(temp.charAt(i)) == -1)
                break;
            if(i + 1 == len)
                list.add(temp);
        }
    }
}
  1. 將鍵盤各行字元存入“frist、second、third”

  2. 遍歷字元陣列 words[],判斷單詞是否符合條件

  3. list轉換為String[] ,返回結果