博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 151:Reverse Words in a String
阅读量:4149 次
发布时间:2019-05-25

本文共 1125 字,大约阅读时间需要 3 分钟。

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space

分析:

对一个字符串中得单词进行翻转,首先必须从字符串中分解出单词,然后将每个词压入堆栈,再依次弹出即可。

代码如下,运行时间约39ms:

class Solution {public:void reverseWords(string &s) {		string result;		int j = 0;		stack
str_stack; const char* pHead = s.c_str(); bool wordStart = false; const char* pStr, *pBegin, *pEnd; for (pStr=pHead; *pStr!='\0'; pStr++) {
			if (!isspace(*pStr) && wordStart==false)
{				wordStart = true;				pBegin = pStr;				continue;			}			if (isspace(*pStr) && wordStart == true)			{				wordStart = false;				pEnd = pStr;				str_stack.push(s.substr(pBegin-pHead, pEnd-pBegin));			}		}		if (wordStart == true)		{			wordStart = false;			pEnd = pStr;			str_stack.push(s.substr(pBegin-pHead, pEnd-pBegin));		}		s.clear();		if (str_stack.size() > 0)		{						char space = ' ';			while (!str_stack.empty())			{				string stmp = str_stack.top();				str_stack.pop();			if (s.length() != 0)				{					s.push_back(space);				}				s = s + stmp;			}		}	}};

转载地址:http://gyxti.baihongyu.com/

你可能感兴趣的文章
Java入门之编程基础(五)
查看>>
Java入门之面对对象
查看>>
Java入门之API的使用及String 和StringBuilder类的常见方法
查看>>
Java入门之对象数组及集合概述
查看>>
Java入门之IO流(输入流和输出流)
查看>>
Java编程案例之学生管理系统
查看>>
Java SE之静态和代码块
查看>>
关于webService的一些理解
查看>>
项目管理工具的使用
查看>>
SpringDataJpa原理及使用
查看>>
懒加载错误的三种处理方案
查看>>
消息队列ActiveMQ的使用
查看>>
定时发短信(quartz框架,阿里大于)
查看>>
常用网址
查看>>
springmvc和mybatis整合(总结)
查看>>
string-boot详解
查看>>
El表达式详解
查看>>
shiro框架
查看>>
类的设计技巧
查看>>
java中跳出外循环或者跳出代码块的方法
查看>>