Monday, September 14, 2015

Longest Common Prefix | Leetcode

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

---

Solution: Use a double for-loop. The outer loop is from the first character to the last character of each string. The inner loop is for each string in the array. Whenever we find an end of any string, or find any string having a different character, stop looping and return the anwer.
public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";
        
        StringBuilder sb = new StringBuilder();

        OUTER:
        for (int i = 0;; i++) {
            if (i >= strs[0].length()) break;
            char c = strs[0].charAt(i);
            
            for (int j = 1; j < strs.length; j++) {
                if (i >= strs[j].length()) break OUTER;
                if (strs[j].charAt(i) != c) break OUTER;
            }
            
            sb.append((char) c);
        }
        
        return sb.toString();
    }
}

No comments: