Longest Common Prefix (Java)

  • 0

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

    Input: "edwardshi", "edward", "edwar", "edwardshidd"
    Output: "edwar"

    public static String longestCommonPrefix(String s[]){
    	if(s==null || s.length == 0) return null;
    	String res = s[0];
    	for(int i=1; i<s.length; i++){
    		while(s[i].indexOf(res, 0) != 0){
    			res = res.substring(0, res.length() - 1);
    	return res;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.