LeetCode 之 Reverse Words in a String — C 實現

Reverse Words in a String

 

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
將給定字符串按 word 翻轉。

例如:

輸入字符串 s = "the sky is blue",

返回 "blue is sky the".

如用 C 語言實現,則要求空間複雜度爲 O(1).

說明:

word 定義爲不含空格的字符序列。

輸入字符串中可以首尾可以有空格,但翻轉後的字符串首尾不能含空格。

輸入字符串的 word 中間可能有多個空格,但翻轉後的字符串 word 間只能有一個空格。

分析:

    先翻轉每個 word,再翻轉整個字符串,或者反過來。

翻轉前先去掉字符串尾可能存在的空格,然後翻轉每個 word,再翻轉整個字符串,最後去掉多餘的空格。

<pre name="code" class="cpp">void reverseWords(char *s) {
    char *pstart = NULL, *pend = NULL;
    char temp = 0;
    int hasword = 0;
    char *pwordstart = s;
    char *ps = s;
    
    if(!s) /*空*/
        return;
        
   while(*ps)
    {
        if(*ps != ' ') /*word*/
        {
            hasword = 1;
            pstart = ps++; /*一個word開頭*/
            while(*ps && *ps != ' ')
            {
                ++ps;
            }
            pend = ps-1; /*一個word結尾*/
            for(; pstart < pend; ++pstart,--pend) /*翻轉一個word*/
            {
                temp = *pstart;
                *pstart = *pend;
                *pend = temp;
            }
        }
        else
        {
            ++ps;
        }
    }
    
    if(hasword == 0)
    {
        *s = '\0';
        return;
    }
    
    while(*--ps == ' '); /*查找非空字符串結尾*/
    *++ps = '\0';
  
    for(pstart = s, pend = ps-1; pstart < pend; ++pstart,--pend)
    {
        temp = *pstart;
        *pstart = *pend;
        *pend = temp;
    }

    ps = s;
    while(*pwordstart)
    {
        if(*pwordstart == ' ' && *(pwordstart+1) == ' ') /*連着空格,不賦值*/
        {
            ++pwordstart;
        }
        else if(*pwordstart == ' ' && *(pwordstart+1) == '\0')
        {
            break;
        }
        else
        {
            *ps = *pwordstart;
            ++pwordstart;
            ++ps;
        }
    }
    *ps = '\0';
    
    return;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章