【问题标题】:Remove Blank spaces in a string in O(n)在 O(n) 中删除字符串中的空格
【发布时间】:2011-03-06 15:23:39
【问题描述】:

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

TIA, 普拉文

【问题讨论】:

标签: c string complexity-theory


【解决方案1】:

您的方法听起来不错,并且符合要求。

【讨论】:

    【解决方案2】:

    这种方法很好。 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 字符串的未定义行为,但在任何就地修改中都会出现这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 2011-09-21
      • 2017-11-20
      相关资源
      最近更新 更多