鱼C论坛

 找回密码
 立即注册
查看: 1688|回复: 1

[技术交流] C++刷剑指offer(面试题58 - I. 翻转单词顺序)【数据结构】

[复制链接]
发表于 2020-3-31 18:31:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 糖逗 于 2020-5-8 18:12 编辑

题目描述:
  1. 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。

  2.  

  3. 示例 1:

  4. 输入: "the sky is blue"
  5. 输出: "blue is sky the"
  6. 示例 2:

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

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

  15. 说明:

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

  19. 来源:力扣(LeetCode)
  20. 链接:https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof
  21. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码



  1. #include<string>
  2. #include<vector>
  3. #include<deque>
  4. #include<iostream>

  5. using namespace std;

  6. string solution(string input){
  7.         string res = "";
  8.         string temp = "";
  9.         deque<string> store;
  10.         for(int i =0; i < input.size(); i++){
  11.                 if(input[i] != ' '){
  12.                         temp += input[i];
  13.                 }
  14.                 if(input[i] == ' ' || i == input.size()-1){
  15.                         if(temp != ""){
  16.                                 store.push_back(temp);       
  17.                         }
  18.                         temp = "";       
  19.                 }
  20.         }

  21.         int size = store.size();
  22.         for(int j = 0; j < size; j++){
  23.                 res += store.back() + ' ';
  24.                 store.pop_back();
  25.         }
  26. //去除首尾空格
  27.         res.erase(0,res.find_first_not_of(" "));
  28.     res.erase(res.find_last_not_of(" ") + 1);
  29.         return res;
  30.        
  31. }

  32. int main(void){
  33.         string input;
  34.         getline(cin, input);
  35.         string res = solution(input);
  36.         cout << res << endl;
  37.        
  38.         return 0;
  39. }
复制代码



参考链接:https://www.cnblogs.com/ylwn817/articles/1967689.html

注意事项:
1.要去除首尾空格。
2.多个空格要当一个空格处理。

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-3-31 18:32:37 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-7 08:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表