Skip to content

Latest commit

 

History

History
26 lines (19 loc) · 524 Bytes

14. Longest Common Prefix.md

File metadata and controls

26 lines (19 loc) · 524 Bytes

14. Longest Common Prefix

Problem

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

tag:

Solution

java

    public String longestCommonPrefix(String[] strs) {
        if(strs==null || strs.length==0) return "";
        StringBuilder sb = new StringBuilder(strs[0]);
        for(int i=1; i<strs.length; i++) {
            while(!strs[i].startsWith(sb.toString())) sb.deleteCharAt(sb.length()-1);
        }
        return sb.toString();
    }

go