【leetcode】Reverse Words in a String(hard)☆

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

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

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.

 

思路:翻转的思路是很清楚的,就是卡在空格上了。结果专门先循环一遍来去掉空格。

注意,必须改变指针中所对应的值才能改变字符串。

void reverse(char * s, char * e)
{
    while(s < e)
    {
        char tmp = *s;
        *s = *e;
        *e = tmp;
        s++; e--;
    }
}

void reverseWords(char *s) {
    //先专门处理空格
    char * p = s;
    char * snew = s;
    while(*p != '\0')
    {
        if(*p != ' ') *snew++ = *p++;
        else if(snew == s) p++; //开始处遇到空格
        else if(*(snew - 1) == ' ') p++; //已经有了一个空格
        else *snew++ = *p++;
    }
    *snew = '\0';
    if(*(snew - 1) == ' ') *(snew - 1) = '\0';

    //翻转
    char *ss = s;
    int start = 0, end = 0;
    while(*ss != '\0')
    {
        while(*ss != ' ' && *ss != '\0')
        {
            ss++;  end++;
        }
        reverse(s + start, s + end - 1);
        if(*ss != '\0')
        {
            ss++; end++; start = end;
        }
    }
    reverse(s, s + end - 1);
}

 

看看大神的:不用先去除空格,而是在遍历的过程中用end来更新字符串,去掉空格。

// reverses the part of an array and returns the input array for convenience
public char[] reverse(char[] arr, int i, int j) {
    while (i < j) {
        char tmp = arr[i];
        arr[i++] = arr[j];
        arr[j--] = tmp;
    }
    return arr;
}

public String reverseWords(String s) {
    // reverse the whole string and convert to char array
    char[] str = reverse(s.toCharArray(), 0, s.length()-1);
    int start = 0, end = 0; // start and end positions of a current word
    for (int i = 0; i < str.length; i++) {
        if (str[i] != ' ') { // if the current char is letter 
            str[end++] = str[i]; // just move this letter to the next free pos
        } else if (i > 0 && str[i-1] != ' ') { // if the first space after word
            reverse(str, start, end-1); // reverse the word
            str[end++] = ' '; // and put the space after it
            start = end; // move start position further for the next word
        }
    }
    reverse(str, start, end-1); // reverse the tail word if it's there
    // here's an ugly return just because we need to return Java's String
    // also as there could be spaces at the end of original string 
    // we need to consider redundant space we have put there before
    return new String(str, 0, end > 0 && str[end-1] == ' ' ? end-1 : end);
}

 

posted @ 2015-04-17 16:08  匡子语  阅读(274)  评论(0编辑  收藏  举报