Skip to content
New issue

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

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

Already on GitHub? # to your account

左旋转字符串 #2

Open
Bulandent opened this issue Jan 3, 2021 · 0 comments
Open

左旋转字符串 #2

Bulandent opened this issue Jan 3, 2021 · 0 comments

Comments

@Bulandent
Copy link
Owner

Bulandent commented Jan 3, 2021

左旋转字符串

难度:简单
来源:剑指 Offer 58 - II

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串 abcdefg 和数字 2 ,该函数将返回左旋转两位得到的结果 cdefgab

示例 1:

输入: s = "abcdefg", k = 2
输出: "cdefgab"

示例 2:

输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"

限制:

1 <= k < s.length <= 10000

题解一:字符串切片

/**
 * @param {string} s
 * @param {number} n
 * @return {string}
 */
var reverseLeftWords = function(s, n) {
    return (s + s).substr(n, s.length)
};
  • 时间复杂度:,执行用时:84 ms
  • 空间复杂度:,内存消耗:38.9 MB

题解二:遍历+余数

/**
 * @param {string} s
 * @param {number} n
 * @return {string}
 */
var reverseLeftWords = function(s, n) {
    let res = []
    for(let i = n, l = n + s.length; i < l; i++) {
        res.push(s.charAt( i % s.length ))
    }
    return res.join('')
};
  • 时间复杂度:,执行用时:80 ms
  • 空间复杂度:,内存消耗:40.6 MB
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

1 participant