gpt4 book ai didi

c - 在 O(n) 中删除字符串中的空格

转载 作者:行者123 更新时间:2023-12-02 06:24:31 25 4
gpt4 key购买 nike

如何去除复杂度为 O(n) 的字符串中的空格。我的方法是使用两个索引。一个人将遍历到字符串的长度。只有当遇到非空白字符时,其他才会递增。但我不确定这种方法。

TIA,普拉文

最佳答案

这种方法很好。 O(n) 要求只是意味着运行时间与项目数量成正比,在这种情况下,项目数量意味着字符串中的字符数量(假设您指的是时间复杂度,这是一个相当安全的赌注)。

伪代码:

def removeSpaces (str):
src = pointer to str
dst = src
while not end-of-string marker at src:
if character at src is not space:
set character at dst to be character at src
increment dst
increment src
place end-of-string marker at dst

基本上就是您要尝试做的事情。

因为它有一个只依赖于字符数的循环,所以确实是O(n)的时间复杂度。


下面的 C 程序展示了这一点:

#include <stdio.h>

// Removes all spaces from a (non-const) string.

static void removeSpaces (char *str) {
// Set up two pointers.

char *src = str;
char *dst = src;

// Process all characters to end of string.

while (*src != '\0') {
// If it's not a space, transfer and increment destination.

if (*src != ' ')
*dst++ = *src;

// Increment source no matter what.

src++;
}

// Terminate the new string.

*dst = '\0';
}

// Test program.

int main (void)
{
char str[] = "This is a long string with lots of spaces... ";
printf ("Old string is [%s]\n", str);
removeSpaces (str);
printf ("New string is [%s]\n", str);
return 0;
}

运行这个给你:

Old string is [This is a long    string with    lots of spaces...   ]
New string is [Thisisalongstringwithlotsofspaces...]

请注意,如果字符串中没有空格,它只会将每个字符复制到自身上。您可能认为可以通过检查 src == dst 而不是复制来优化它,但您可能会发现检查与复制一样昂贵。而且,除非您经常复制数兆字节的字符串,否则性能不会成为问题。

另外请记住,对于 const 字符串,这将是未定义的行为,但在任何就地修改中都是如此。

关于c - 在 O(n) 中删除字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3090316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com