Longest Common Prefix

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

Its a simple question, just scan through all the strings, compare the first element, then second, then third and so on. If found a mismatch or reached the end of string, return the result.

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0)
            return "";
        if (strs.length == 1)
            return strs[0];
        StringBuilder res = new StringBuilder();
        int ptr = 0;
        while(ptr != strs[0].length()) {
            char c = strs[0].charAt(ptr);
            for (String s : strs) {
                if (ptr == s.length())
                    return new String(res);
                if (s.charAt(ptr) != c)
                    return new String(res);
        return new String(res);

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s