14.Longest Common Prefix

題目連接:https://leetcode.com/problems/longest-common-prefix/description/數組

題目大意:找出字符串數組的最長公共前綴。與ide

法一:豎向比較,也就是對於每一個字符串,都對應的比較對應下標的字符,一旦不等,則公共前綴到此結束。代碼以下(耗時12ms):spa

 1     public String longestCommonPrefix(String[] strs) {
 2         int i = 0;
 3         String res = "";
 4         if(strs.length == 0 || strs[0].length() == 0) {
 5             return res;
 6         }
 7         while(true) {
 8             char ch = strs[0].charAt(i);
 9             boolean flag = false;
10             for(int j = 1; j < strs.length; j++) {
11                 //若是遍歷到某個字符串的結尾字符,則到此結束
12                 if(i == strs[j].length()) {
13                     flag = true;
14                     break;
15                 }
16                 //若是遍歷到字符不相等,則到此結束
17                 if(strs[j].charAt(i) != ch) {
18                     flag = true;
19                     break;
20                 }
21             }
22             if(flag == true) {
23                 break;
24             }
25             res += String.valueOf(ch);
26             i++;
27         }
28         return res;
29     }
View Code

更多解法見https://leetcode.com/problems/longest-common-prefix/solution/3d

相關文章
相關標籤/搜索