【剑指offer】32.翻转单词序列
总目录:
1.问题描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“nowcoder. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a nowcoder.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
数据范围:1≤n≤100
进阶:空间复杂度 O(n) O(n) ,时间复杂度 O(n) O(n) ,保证没有只包含空格的字符串
2.问题分析
1两次翻转,需要用到reverse(startIndex,endIndex),
注意reverse函数需要引用#include <algorithm>,翻转范围为左闭右开的[startIndex,endIndex)
2用栈翻转单词与单词的顺序,主要是考察字符串的剪切、拼接方法
3.代码实例
两次翻转

1 class Solution { 2 public: 3 const char cSplit = ' '; 4 string ReverseSentence(string str) { 5 int strLen = str.length(); 6 7 //第一次翻转 8 reverse(str.begin(), str.end()); 9 10 //第二次翻转 11 int startIndex = 0; 12 int endIndex = 0; 13 for (int i = 0; i < strLen; i++) { 14 //更新中止索引 15 endIndex = i; 16 17 //未遇到空格 18 if (str[endIndex] != cSplit) { 19 //是否到了最后一位,是则需要翻转 20 if (endIndex == (strLen - 1)) { 21 endIndex++; 22 } else { 23 continue; 24 } 25 } 26 27 //翻转当前段 28 reverse(str.begin() + startIndex, str.begin() + endIndex); 29 30 //更新起始地址 31 startIndex = endIndex + 1; 32 } 33 34 return str; 35 } 36 };
栈

1 class Solution { 2 public: 3 const char cSplit = ' '; 4 string ReverseSentence(string str) { 5 int strLen = str.length(); 6 7 stack<string> strBuf; 8 int startIndex = 0; 9 for (int i = 0; i < strLen; i++) { 10 //如果没有遇到分隔符 11 if (str[i] != cSplit) { 12 //是否到了结尾 13 if (i == (strLen - 1)) { 14 i++; 15 } else { 16 continue; 17 } 18 } 19 20 strBuf.push(str.substr(startIndex, i - startIndex)); 21 startIndex = i + 1; 22 } 23 24 //逐个拼接栈中的元素 25 string newStr=""; 26 while(!strBuf.empty()){ 27 newStr.append(strBuf.top()); 28 strBuf.pop(); 29 30 //添加分隔符号 31 if(!strBuf.empty()){ 32 newStr.append(&cSplit); 33 } 34 } 35 36 return newStr; 37 } 38 };
本文作者:啊原来是这样呀
本文链接:https://www.cnblogs.com/OhOfCourse/p/16890125.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步