zoukankan      html  css  js  c++  java
  • 字符串单词翻转

    题目描述

    给定一个字符串,逐个翻转字符串中的每个单词。

    说明:

    无空格字符构成一个 单词 。
    输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
    如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
     

    示例 1:

    输入:"the sky is blue"
    输出:"blue is sky the"
    示例 2:

    输入:"  hello world!  "
    输出:"world! hello"
    解释:输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
    示例 3:

    输入:"a good   example"
    输出:"example good a"
    解释:如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reverse-words-in-a-string

    解题思路

    可以使用栈或者双端队列作为数据结构存储单词,将其反向拼接为需要的结果,但是空间复杂度为 o(n),如果要求 o(1)的复杂度,只能再string 本身进行反转覆盖,并且同时去除重复空格,下面代码是o(1)的解法,使用双指针思想记录原始字符串的末尾和翻转后的字符串的开始位置。

    string reverseWords(string s) {
            int tail = s.size()-1;
            int end = tail;
            int gip, i;
            while(end >= 0) {
                gip = 0;
                string word = "";
                for(i = 0; i <= end; i++) {
                    if(s[i] == ' ' && word != "") {
                        while(s[i++] == ' ') {
                            gip ++;
                        }
                        break;
                    }
                    if(s[i] == ' ') {
                        gip ++;
                        continue;
                    }
                    word += s[i];
                    gip++;
                }
                for(i = gip; i <= end; i++) s[i-gip] = s[i];
                end -= gip;
                i = tail-word.size()+1;
                tail = i-2;
                if(i>0) s[i-1] = ' ';
                for(auto c : word) s[i++] = c;
            }
            s.erase(0, tail+2);
            return s;
        }
  • 相关阅读:
    应用部署架构演进【转载】
    TiDB 学习笔记一(运维管理)
    c++ strcmp函数
    C++ sort()函数
    C++ 遍历set的三种方式
    nvcc fatal : '--ptxas-options=-v': expected a number
    PAT A1039 Vector的使用
    C++ set
    C++ int与string互转换
    C++%f和%lf的区别
  • 原文地址:https://www.cnblogs.com/zz-zhang/p/13926822.html
Copyright © 2011-2022 走看看