Leetcode: Longest Common Prefix

来源:互联网 发布:什么是棋牌源码 编辑:程序博客网 时间:2024/06/16 22:35

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

public class Solution {    public String longestCommonPrefix(String[] strs) {        if (strs == null) {            return null;        }                if (strs.length == 0) {            return "";        }                String res = strs[0];        for (int i = 1; i < strs.length; i++) {            String curr = strs[i];            StringBuilder sb = new StringBuilder();            int j = 0;            while (j < res.length() && j < curr.length() && res.charAt(j) == curr.charAt(j)) {                sb.append(res.charAt(j));                j++;            }            res = sb.toString();        }        return res;    }}


0 0
原创粉丝点击