Longest Common Prefix

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 || strs.length == 0) return ""; 
        //set the pre as the first string; 
        //compare it with the rest of the strings
        String pre = strs[0];
        //represent which str is being traversed 
        int i = 1; 
        while (i < strs.length) {
            while (strs[i].indexOf(pre) != 0){
                /*
                 * If pre is prefix of str[i]
                 * str.indexOf() should return 0 (leftmost instance).
                 * If the return is not 0, shorten pre until it is.
                 */
                pre = pre.substring(0, pre.length() - 1); 
            }
            if (pre.length() == 0) return pre;
            i++; 
        }
        return pre; 
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s