LeetCode 14 – Longest Common Prefix

Posted on December 25, 2013

Last updated on December 25, 2013

Solution to LeetCode Longest Common Prefix problem.

This is just an implementation question, no fancy algorithm used here.

public String longestCommonPrefix(String[] strs) {
  if(strs.length == 0) return "";
  if(strs.length == 1) return strs[0];
  int last = 0;

  loop:
    while(true){
      for(int i = 0; i < strs.length-1; i++){
        String s1 = strs[i];
        String s2 = strs[i+1];
        if(last >= s1.length() || last >= s2.length()) break loop;
        if( s1.charAt(last) != s2.charAt(last)) break loop;
      }
      last++;
    }
    return strs[0].substring(0,last);
  }
Longest Common Prefix
Markdown SHA1: 4c7f07c7eeb2c247eda8c13e4e8e60fea37902d1