Longest Common Prefix

来源:互联网 发布:手机定位软件开发 编辑:程序博客网 时间:2024/05/18 03:05

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

Show Tags

Have you met this question in a real interview?


思路: 很简单的一道题, 找到 字符串数组中 的最长前缀。 从第一个字符串开始, 和下一个字符串比较, 保留下来相同的字串。

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++){            int min = Math.min(ret.length(), strs[i].length());            int j = 0;            while(j < min && ret.charAt(j) == strs[i].charAt(j)){                j++;            }            ret = ret.substring(0, j);        }        return ret;    }}


0 0
原创粉丝点击