Skip to content

14. Longest Common Prefix

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

js
/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
  if (!strs.length) {
    return ''
  }
  var i = 1
  var prefix = ''
  while (i <= strs[0].length && (prefix = strs[0].substring(0, i))) {
    var isCommonPrefix = strs.every(str => str.startsWith(prefix))
    if (isCommonPrefix) {
      i++
    } else {
      return prefix.substring(0, prefix.length - 1)
    }
  }
  return prefix
}
py
class Solution(object):

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

        i, prefix = 1, ''
        while i <= len(strs[0]):
            prefix = strs[0][0:i]
            for str in strs[1:]:
                if prefix != str[0:i]:
                    return prefix[0:-1]
            i += 1
        return prefix
go
func longestCommonPrefix(strs []string) string {
	if len(strs) == 0 {
		return ""
	}

	i := 1
	prefix := ""

	for i <= len(strs[0]) {
		prefix = strs[0][:i]
		commonPrefix := true

		for i := 0; i < len(strs) && commonPrefix; i++ {
			if len(prefix) > len(strs[i]) {
				commonPrefix = false
			} else {
				commonPrefix = prefix == strs[i][:len(prefix)]
			}
		}

		if commonPrefix {
			i++
		} else {
			return prefix[:len(prefix)-1]
		}
	}

	return prefix
}