Java - Write code to Returns the longest common prefix for two Strings or "" if no prefix is shared

Requirements

Write code to Returns the longest common prefix for two Strings or "" if no prefix is shared

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String one = "book2s.com";
        String two = "book2s.com";
        System.out.println(longestCommonPrefix(one, two));
    }//from ww w .  jav a  2s .c  o  m

    /**
     * Returns the longest common prefix for two Strings or <tt>""</tt> if no prefix is shared
     *
     * @param one The one String
     * @param two The other String
     *
     * @return The longest common prefix, or ""
     */
    public static String longestCommonPrefix(String one, String two) {
        if (one.equals(two)) {
            return one;
        }
        if (one.equals("") || two.equals("")) {
            return "";
        }

        String currentPrefix = "";
        int size = 0;
        while (one.startsWith(currentPrefix)
                && two.startsWith(currentPrefix)) {
            size++;
            currentPrefix = one.substring(0, size);
        }
        return one.substring(0, size - 1);
    }
}

Related Exercise