167.Longest Common Prefix(最长的共同前缀)

题目:

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

编写一个函数来查找字符串数组中最长的公共前缀字符串。

If there is no common prefix, return an empty string "".

如果没有公共前缀,则返回空字符串“”。

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

所有给定的输入都是小写字母a-z。

解答:

方法一:横向遍历

 1 class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if(strs==null || strs.length==0) return "";
 4         String prefix=strs[0];
 5         for(int i=1;i<strs.length;i++){
 6             while(strs[i].indexOf(prefix)!=0) 
 7                 prefix=prefix.substring(0,prefix.length()-1); 
 8         }
 9         return prefix;
10     }
11 }

方法二:

 1 class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if(strs==null || strs.length==0) return "";
 4         for(int i=0;i<strs[0].length();i++){
 5             char c=strs[0].charAt(i);
 6             for(int j=1;j<strs.length;j++){
 7                 if(i==strs[j].length() || strs[j].charAt(i)!=c)
 8                     return strs[0].substring(0,i);
 9             }
10         }
11         return strs[0];
12     }
13 }

详解:

方法一:

str.indexOf(substr)用于字符串中子串的查找,返回子字符串substr在父串str中首次出现的位置,从0开始,没有返回-1。

过程是:flower -> flowe -> flow -> flo -> fl

以第一个字符串为标准,依次判断是否是前缀,如果不是就从末尾去掉一个字符,直到为前缀。

方法二:

从第一个字符开始遍历,直到找到所有字符串出现不一样的字符。

过程:f -> fl -> flo和fli不一样了,就返回fl

posted @ 2018-09-13 20:36  chan_ai_chao  阅读(135)  评论(0编辑  收藏  举报