14.Longest Common Prefix

题目链接:https://leetcode.com/problems/longest-common-prefix/description/

题目大意:找出字符串数组的最长公共前缀。与

法一:竖向比较,也就是对于每个字符串,都对应的比较对应下标的字符,一旦不等,则公共前缀到此结束。代码如下(耗时12ms):

 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/

原文地址:https://www.cnblogs.com/cing/p/8528706.html