LeetCode //151. Reverse Words in a String

151. Reverse Words in a String

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

 

Example 1:

Input: s = “the sky is blue”
Output: “blue is sky the”

Example 2:

Input: s = " hello world "
Output: “world hello”
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = “a good example”
Output: “example good a”
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints:

  • 1 < = s . l e n g t h < = 1 0 4 1 <= s.length <= 10^4 1<=s.length<=104
  • s contains English letters (upper-case and lower-case), digits, and spaces ’ '.
  • There is at least one word in s.

From: LeetCode
Link: 151. Reverse Words in a String


Solution:

Ideas:
In this code, we start from the end of the string and skip any spaces. We then find the start of each word and copy it to the result. We add a space before each word except the first one. Finally, we add the null terminator at the end of the result. This code correctly handles leading or trailing spaces and multiple spaces between words.
Code:
char* reverseWords(char * s){
    int len = strlen(s);
    char *result = (char*)malloc((len + 1) * sizeof(char));
    int start = len - 1;
    int end = len - 1;
    int index = 0;

    while(start >= 0){
        // Skip spaces at the end and between words
        while(start >= 0 && s[start] == ' ') start--;

        // If there are spaces in the result, add a space to separate words
        if(index > 0 && start >= 0) result[index++] = ' ';

        end = start;

        // Find the start of the word
        while(start >= 0 && s[start] != ' ') start--;

        // Copy the word to the result
        for(int i = start + 1; i <= end; i++){
            result[index++] = s[i];
        }
    }

    // Add the null terminator
    result[index] = '\0';

    return result;
}

你可能感兴趣的:(LeetCode,leetcode,算法,c语言)