【leetcode】14. Longest Common Prefix

题目描述:

Write a function to find the longest common prefix string amongst an array of strings.

解题思路:

这道题很简单,分两步:

1. 找出所有字符串中长度最小的那个字符串的值(可能的结果的最大值,保证查找时不出现越界);

2.依次遍历所有字符串的第i个位置上的值。判断是否满足要求。

具体代码:

 1 public class Solution {
 2     public static String longestCommonPrefix(String[] strs) {
 3         if(strs.length==0)
 4             return "";
 5         if(strs.length==1)
 6             return strs[0];
 7         //用来保存已经找出的结果
 8         StringBuilder sb = new StringBuilder();
 9         //找出所有字符串中长度最小的那个字符串的值
10         int min=Integer.MAX_VALUE;
11         for(int i=0;i<strs.length;i++){
12             if(strs[i].length()<min){
13                 min=strs[i].length();
14             }
15         }
16         //依次遍历所有字符串的第i个位置上的值,若所有的字符串在该位置上值都一样,就表明这个位置的字符包含在最小共同前缀内。否则说明该位置开始出现不一致的字符串,查找结束。
17         for(int i=0;i<min;i++){
18             char ch=strs[0].charAt(i);
19             //用来标记是否结束查找的变量
20             boolean key=true;
21             for(int j=1;j<strs.length&&key;j++){
22                 if(strs[j].charAt(i)!=ch){
23                     key=false;
24                 }
25             }
26             if(key){
27                 sb.append(ch);
28             }
29             else{
30                 break;
31             }
32         }
33         return sb.toString();
34     }
35 }
原文地址:https://www.cnblogs.com/godlei/p/5636453.html