Leetcode: Longest Common Prefix

来源:互联网 发布:浪漫喜剧电影 知乎 编辑:程序博客网 时间:2024/05/20 06:38

Problem:

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




Solution:

         Idea: compare each character of all the strings.


Code:

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

0 0
原创粉丝点击