Longest Common Prefix

Source

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

Java

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs==null || strs.length==0) return "";
        StringBuilder sb = new StringBuilder();

        String str = strs[0];
        for(int i=0; i<str.length(); i++){
            char c = str.charAt(i);
            for(String s: strs){
                if(i>=s.length() || s.charAt(i)!=c){
                    return sb.toString();
                } 
            }
            sb.append(c);
        }
        return sb.toString();
    }
}