Find longest common prefix?

前端 未结 9 1884
忘掉有多难
忘掉有多难 2020-12-10 03:50

In two strings:

\"Mary Had a Little Lamb\"
\"Mary Had a Big Lamb\"

should return

\"Mary Had a \"

9条回答
  •  庸人自扰
    2020-12-10 04:17

    public class Test{
     public static void main(String[] args){
        String s1 = "Mary Had a Little Lamb";
        String s2 = "Mary Had a Big Lamb";
        int minStrLen = s1.length();
        if ( minStrLen > s2.length()){
            minStrLen = s2.length();
        }
    
        StringBuilder output = new StringBuilder();
        for(int i=0; i

    This may not be the optimum solution, but this is easy to understand and program.

    I borrowed this idea from the list merging technique of merge-sort algorithm. If you read little about list merging technique you will better understand the logic of my algorithm.

提交回复
热议问题