Skip to content

14. Longest Common Prefix

https://leetcode.com/problems/longest-common-prefix/

c++
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string prefix;
        for (int i = 0; i < strs[0].length(); i++) {
            char c = strs[0][i];
            for (int j = 1; j < strs.size(); j++) {
                if (i >= strs[j].length() || c != strs[j][i]) {
                    return prefix;
                }
            }
            prefix += c;
        }
        return prefix;
    }
};
go
func longestCommonPrefix(strs []string) string {
  if len(strs) == 0 {
    return ""
  }

  prefix := ""
  for i := 0; i < len(strs[0]); i++ {
    c := strs[0][i]
    for j := 1; j < len(strs); j++ {
      if i >= len(strs[j]) || c != strs[j][i] {
        return prefix
      }
    }
    prefix += string(c)
  }
  return prefix
}
js
/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
  if (!strs.length) {
    return ''
  }

  let prefix = ''
  for (let i = 0; i < strs[0].length; i++) {
    const c = strs[0][i]
    for (let j = 1; j < strs.length; j++) {
      if (i >= strs[j].length || strs[j][i] !== c) {
        return prefix
      }
    }
    prefix += c
  }
  return prefix
}
py
class Solution(object):

    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''

        prefix = ''
        for i in range(len(strs[0])):
            c = strs[0][i]
            for j in range(1, len(strs)):
                if i >= len(strs[j]) or strs[j][i] != c:
                    return prefix
            prefix += c
        return prefix