LeetCode 14 Longest Common Prefix

14. Longest Common Prefix

My Submissions
Question Editorial Solution
Total Accepted: 94641  Total Submissions: 338784  Difficulty: Easy

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

Subscribe to see which companies asked this question

Show Tags
Have you met this question in a real interview? 
Yes
 
No

Discuss


求字符串数组中所有字符串的最长功能前缀


看到了Discuss里这种简单清晰易懂好实现的方法。

使用了jdk的库函数indexOf


public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs==null||strs.length==0)    
            return "";
        String ret=strs[0];
        for(int i=1;i<strs.length;i++){
            while(strs[i].indexOf(ret)!=0)
                    ret=ret.substring(0,ret.length()-1);
        }
        return ret; 
    }
}



你可能感兴趣的:(LeetCode 14 Longest Common Prefix)