Longest Common Prefix

来源:互联网 发布:四大名著排名 知乎 编辑:程序博客网 时间:2024/05/21 10:19

Q:

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

Solution:

public class Solution {    public String longestCommonPrefix(String[] strs) {        if (strs == null || strs.length == 0)            return "";        String prefix = strs[0];        for (int i = 1; i < strs.length; i++) {            int j = 0;            while (j < prefix.length() && j < strs[i].length() && prefix.charAt(j) == strs[i].charAt(j)) {                j++;            }            prefix = prefix.substring(0, j);        }        return prefix;    }}


0 0
原创粉丝点击