Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Longest Common Prefix #12

Open
barretlee opened this issue Jul 14, 2017 · 2 comments
Open

Longest Common Prefix #12

barretlee opened this issue Jul 14, 2017 · 2 comments

Comments

@barretlee
Copy link
Owner

本题难度:★

写一个函数,找出一个字符串数组的最长共同前缀。例如:

给定 ['hi, barret', 'hi, skylar', 'hi, john'],输出 'hi, '
@barretlee
Copy link
Owner Author

function resolve(arr) {
  var commonPrefix = arr[0];
  for (var i = 1, len = arr.length; i < len; i++) {
    if (arr[i].length < commonPrefix.length) {
      commonPrefix = commonPrefix.slice(0, arr[i].length);
    }
    var count = commonPrefix.length;
    while (count--) {
      if (commonPrefix[count] !== arr[i][count]) {
        commonPrefix = commonPrefix.slice(0, count); 
      }
    }
    if (!commonPrefix.length) return '';
  }
  return commonPrefix;
}

var ret = resolve(['hi, barret', 'hi, skylar', 'hi, john']);
console.assert(ret === 'hi, ', ret);

@YabZhang
Copy link

def resolve(seq):
  """
    longest common prefix
  """
    if not seq:
        return ''
    
    result = list(seq[0])
    for item in seq:
        if len(item) < len(result):
            result = result[:len(item)]
        for i in range(len(result)):
            if result[i] != item[i]:
                break
        if i != len(result) - 1:
            result = result[:i]
    return ''.join(result)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants