Longest Common Prefix

来源:互联网 发布:linux监控软件对比 编辑:程序博客网 时间:2024/04/28 17:07

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

Analysis: First compute the common prefix of the first two strings and then use the result compare with the rest of the strings in that array. 

public class Solution {    public String longestCommonPrefix(String[] strs) {        String common = "";        if(strs.length==0) return common;        if(strs.length==1) return strs[0];                // got common prefix from the first two strings        String s0 = strs[0];        String s1 = strs[1];        for(int i=0; i<(s0.length()<=s1.length()?s0.length():s1.length()); i++) {            if(s0.charAt(i)==s1.charAt(i)) common+=s0.charAt(i);            else break;        }        if(common=="") return common;                // iterate the rest strings in the array to got the longest common prefix        for(int j=2; j<=strs.length-1; j++) {            String temp = "";            for(int k=0; k<(common.length()<=strs[j].length()?common.length():strs[j].length()); k++) {                if(common.charAt(k) == strs[j].charAt(k)) {                     temp += strs[j].charAt(k);                }                else {                    if(k==0) return "";                    else break;                }            }            common = temp;        }                return common;    }}



0 0
原创粉丝点击