Longest Common Prefix

Longest Common Prefix

问题:

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

思路:

  简单的string运算

我的代码:

public class Solution {

    public String longestCommonPrefix(String[] strs) {

        if(strs == null || strs.length == 0) return "";

        String comm = strs[0];

        for(int i = 1; i < strs.length; i++)

        {

            comm = getCommon(comm,strs[i]);

        }

        return comm;

    }

    public String getCommon(String left, String right)

    {

        int i = 0;

        while(i < left.length() && i < right.length())

        {

            if(left.charAt(i) == right.charAt(i)) i++;

            else    break;

        }

        return left.substring(0,i);

    }

}
View Code

 

你可能感兴趣的:(long)