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

Pra*_*n S 2 c string complexity-theory

如何删除复杂度为O(n)的字符串中的空格.我的方法是使用两个索引.一个人将穿过绳子长度.只有遇到非空白字符时,其他才会增加.但我不确定这种方法.

TIA,Praveen

pax*_*blo 7

这种方法很好.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
Run Code Online (Sandbox Code Playgroud)

基本上就是你想要做的.

因为它具有仅依赖于字符数的单个循环,所以它确实是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';
}
Run Code Online (Sandbox Code Playgroud)

 

// 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;
}
Run Code Online (Sandbox Code Playgroud)

运行这个给你:

Old string is [This is a long    string with    lots of spaces...   ]
New string is [Thisisalongstringwithlotsofspaces...]
Run Code Online (Sandbox Code Playgroud)

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

还要记住,这将是const字符串的未定义行为,但在任何就地修改中都是这种情况.