【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);
}
时间: 2024-10-11 01:50:52

【leetcode】Reverse Words in a String(hard)☆的相关文章

【leetcode】Reverse Words in a String

问题:给定一个字符串,字符串中包含若干单词,每个单词间由空格分隔,将单词逆置,即第一个单词成为最后一个单词,一次类推. 说明:字符串本身可能包含前导空格或后导空格,单词间可能包含多个空格,要求结果中去掉前导和后导空格,单词间空格只保留一个. 与rotate函数类似,先逆置每个单词,再将所有字符串逆置. void reverseWords(string &s) { if(s.size() == 0) return; char blank = ' '; size_t len = s.size();

【leetcode】Reverse Words in a String (python)

陆陆续续几个月下来,终于把题刷完了,过程中遇到的python的题解很少,这里重新用python实现下,所以题解可能都是总结性的,或者是新的心得,不会仅针对题目本身说的太详细. def reverseWords(self, s): s = ' '.join(s.split()[::-1]) return s [ : :  -1 ] 是将元素进行翻转 [leetcode]Reverse Words in a String (python),布布扣,bubuko.com

【Leetcode】Reverse Vowels of a String

题目链接:https://leetcode.com/problems/reverse-vowels-of-a-string/ 题目: Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode

【Leetcode】Reverse Words in a String JAVA实现

一.题目描述 Given an input string, reverse the string word by word. For example,Given s = "the sky is blue",return "blue is sky the". 二.分析 要注意几点:1.当字符串的头部或者尾部存在空格时,最后都将被消除 2.当两个子字符串之间的空格的个数大于1时,只要保留一个 解题思路:1.首先,将整个字符串进行反转 2.然后,使用split函数对字符串

【LeetCode】Reverse Integer (2 solutions)

Reverse Integer Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 click to show spoilers. Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have alread

【LeetCode】Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note:Given m, n satisfy the following condition:1 ≤ m ≤ n ≤ lengt

【leetcode】reverse Nodes in k-groups

问题: 给定一个链表的头指针,以及一个整数k,要求将链表按每k个为一组,组内进行链表逆置.少于k个的部分不做处理. 分析: 个人觉得问题的重点是熟悉链表的就地逆置操作,就是头插法.其他的考察点如果还有的话,就的细心程度. 实现: void reverseList(ListNode *&pre, ListNode *head) { ListNode *tail = NULL; while (head) { ListNode* next = head->next; head->next =

【LeetCode】Reverse Linked List II 解题报告

[题目] Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n

【Leetcode】Reverse String

题目链接:https://leetcode.com/problems/reverse-string/ 题目: Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". 思路: easy 算法: public String reverseString(String s) { char