删除字符串中的空格 O(n)
如何删除复杂度为 O(n) 的字符串中的空格。 我的方法是使用两个索引。一个人将遍历直到字符串的长度。仅当遇到非空白字符时,Other 才会递增。 但我不确定这种方法。
TIA, 普拉文
How to remove blank spaces in a string with a complexity of O(n).
My approach is using two indexes. One will traverse till length on string. Other will be incremented only when a non-blank character is encountered.
But i am not sure of this approach.
TIA,
Praveen
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个办法很好。 O(n) 要求只是意味着运行时间与项目数量成正比,在本例中意味着字符串中的字符数量(假设您指的是时间复杂度,这是一个相当安全的选择)。
伪代码:
基本上就是您想要做的。
因为它有一个仅依赖于字符数的循环,所以它的时间复杂度确实是 O(n)。
下面的 C 程序显示了这一点
:
运行此命令将为您提供:
请注意,如果字符串中没有空格,它只会将每个字符复制到自身上。您可能认为可以通过检查是否 src == dst 而不是复制来优化它,但您可能会发现检查与复制一样昂贵。而且,除非您经常复制多兆字节的字符串,否则性能在这里不会成为问题。
另请记住,对于
const
字符串来说,这将是未定义的行为,但在任何就地修改中都会出现这种情况。This approach is fine. The O(n) requirement simply means that the running time is proportional to the number of items which in this case means the number of characters in the string (assuming you mean time complexity which is a fairly safe bet here).
The pseudocode:
is basically what you're trying to do.
Because it has a single loop dependent only on the number of characters, it is indeed O(n) time complexity.
The following C program shows this in action:
Running this gives you:
Note that, if there are no spaces in the string, it simply copies every character over itself. You might think that you could optimise it by checking if
src == dst
and not copying but you'll probably find the check is as expensive as the copy. And, unless you're frequently copying multi-megabyte strings, performance won't be an issue here.Also keep in mind this will be undefined behaviour with
const
strings but that would be the case in any in-place modification.你的方法听起来不错,并且满足要求。
Your approach sounds fine, and meets the requirement.