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

[字符串] #12

Open
Linjiayu6 opened this issue Jul 19, 2020 · 3 comments
Open

[字符串] #12

Linjiayu6 opened this issue Jul 19, 2020 · 3 comments

Comments

@Linjiayu6
Copy link
Owner

Linjiayu6 commented Jul 19, 2020

1 - 14. 最长公共前缀

前缀相同即可

//  两两比较
var twoMatch = function (str1, str2) {
    if (!str1 || !str2) return ''
    var i = 0
    while (i < str1.length && i < str2.length) {
        if (str1[i] !== str2[i]) break
        i += 1
    }
    return i === 0 ? '' : str1.slice(0, i)
}

var longestCommonPrefix = function(strs) {
    if (strs.length === 0) return ''
    if (strs.length === 1) return strs[0]
    var prev = strs[0]
    for (let i = 1; i < strs.length; i++) {
        prev = twoMatch(prev, strs[i])
        if (prev === '') return ''
    }
    return prev
};
@Linjiayu6
Copy link
Owner Author

Linjiayu6 commented Jul 19, 2020

2 - 回文判断

类似 Linjiayu6/FE-Notes#11 (comment)
字符串判断是否回文

api使用

function fn(str) {
    if (str.length === 0 || str.length === 1) return true;
    return str.split('').reverse().join('') === str;
}

不使用api

function fn(str) {
    if (str.length === 0 || str.length === 1) return true;
    var i = 0, j = str.length - 1
    while (i < j) {
        if (str[i] !== str[j]) return false
        i += 1
        j -= 1
    }
    return true
}

@Linjiayu6
Copy link
Owner Author

@Linjiayu6
Copy link
Owner Author

Linjiayu6 commented Jul 19, 2020

4 - 415. 字符串相加

/**
 * 从尾部开始指针计算
 * [192] [19]
 * i = num1.length - 1, j = num2.length - 1
 * 循环条件 i >= 0 || j >= 0 只有当都小于0, 才结束
 * x = 2, y = 9, count = 0
 * => result = 1 count 1
 * x = 9, y = 1, count = 1
 * => result = 11, count = 1
 * x = 1, y = 0(单独补0), count = 1
 * => result = 211
 * 
 * 最后如果有count还是1的情况, 再最前面补上
 */
var addStrings = function(num1, num2) {
  var i = num1.length - 1, j = num2.length - 1
  var result = ''
  var count = 0
  while (i >= 0 || j >= 0) {
    var x = i >= 0 ? Number(num1[i]) : 0
    var y = j >= 0 ? Number(num2[j]) : 0
    var val = x + y + count
    if (val >= 10) {
      val = val - 10
      result = val.toString() + result
      count = 1
    } else {
      result = val.toString() + result
      count = 0
    }
    i -= 1
    j -= 1
  }
  return count === 1 ? '1' + result : result
};

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

No branches or pull requests

1 participant