天天看點

LeetCode之Keyboard Row

1、題目:

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.

LeetCode之Keyboard Row

Example 1:

1. Input: ["Hello", "Alaska", "Dad", "Peace"]
2. Output: ["Alaska", "Dad"]      

2、代碼實作:

import java.util.ArrayList;
public class Solution {
      public ArrayList<String> resultList;
      //檢驗這個字元串是否全在同一行
      public boolean check(String s1, String s2) {
          if (s1 == null) {
              return false;
          }
          for (int i = 0; i < s1.length(); ++i) {
              if (s2.indexOf(s1.charAt(i)) == -1) {
                  return false;
              }
          }
          return true;
      }
      public  String[] findWords(String[] words) {
          //檢驗字元串數組是否都為null
          if (words == null) {
              return null;
          }
          int length = words.length;
          String s1 = "qwertyuiop";
          String s2 = "asdfghjkl";
          String s3 = "zxcvbnm";
          resultList = new ArrayList<String>();
          //判斷每次
          for (int i = 0; i < length; ++i) {
              String lowerStr = words[i].toLowerCase();
              if (lowerStr != "") {
                  if (s1.indexOf(lowerStr.charAt(0)) != -1) {
                       if(check(lowerStr, s1))
                           resultList.add(words[i]);
                  }
                  if (s2.indexOf(lowerStr.charAt(0)) != -1) {
                     if(check(lowerStr, s2))
                          resultList.add(words[i]);
                  }
                  if (s3.indexOf(lowerStr.charAt(0)) != -1) {
                      if(check(lowerStr, s3))
                            resultList.add(words[i]);
                  } 
              }
          }
          String[] strArr = new String[resultList.size()];
          resultList.toArray(strArr);
          return strArr;
      }
}      

3、遇到的問題:

特麼我一開始把在if後面加了

if(check(lowerStr, s1));      

導緻所有的資料都加進去了,以後要注意,不要亂雞吧寫,在if後面加上;

繼續閱讀