【发布时间】:2020-07-18 16:53:42
【问题描述】:
我正在尝试为以下问题的解决方案获得正确的时间复杂度:
Input: a string contains spaces and words, and an integer M
Output: trim the string so the trimmed string length <= m and no cut-off word.
Sample:
S = "This is JavaScript", M = 10.
Expect: "This is" // because "This is Ja" is invalid, "JavaScript" is cut.
S = "JavaScript", M = 5
Expect: "" // empty because the output "JavaS" is invalid.
S = "JavaScript", M = 10
Expect: "JavaScript"
这是我的代码:
function trimThis(S, M) {
if (M > S.length) return S;
let output = S.slice(); // Making a copy of the input is optional
while (output.length > M) {
const lastSpaceIdx = output.lastIndexOf(' ');
if (lastSpaceIdx !== -1) {
const endIdx = Math.min(lastSpaceIdx, output.length);
output = output.slice(0, endIdx);
}
else return '';
}
// In JS we can also use trimEnd() to remove trailing spaces:
while (output.length > 0 && output[output.length - 1] === ' ') {
output = output.slice(0, -1);
}
return output;
}
我认为总时间复杂度是 O(N),其中 n = len(S),但由于 while 循环,我不确定。
while 循环将运行 O(N - M) 次。在每次迭代中,代码执行 O(N) 操作来查找最后一个空间索引,slice() 操作需要 O(N),所以它看起来像 O(N^2)。然而,在每次迭代之后,字符串变得越来越小。
复制字符串O(N)的时间不会影响整体大O。
【问题讨论】:
-
请解释您的输入,正确输出。什么是截词?
-
谢谢。我已更新问题以使其更清晰。
标签: javascript algorithm big-o