leetcode Online Judge 150题 解答分析之一 Reverse Words in a String

本文提供了一种C++实现的方法来反转字符串中的单词顺序。通过逐个字符扫描并利用双指针技巧,该方法能够有效地处理包括多余空格在内的各种输入情况。

问题

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

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

面试时我应该至少问的问题

  1. What constitutes a word? A sequence of non-space characters constitutes a word.
  2. Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces.
  3. How about multiple spaces between two words? Reduce them to a single space in the reversed string.

 我大概想了下,但是没有问出来,需要改进!

 

代码分析

class Solution {
public:
    static void reverseWords(string &s) 
    {
        int len = s.length();
        string result;
        for(int i= len - 1; i >= 0; )
        {
            int lastend = 0;
            while(i >= 0 && s[i] == ' ') //需要先判断i >=0,否则s[i]会出错
            {
                i--;
            }
            if(i < 0) //这里需要break,因为可能一连串的空格,没有任何字母,这时就应该及时退出
                break;
            lastend = i;
            while(i >= 0 && s[i] != ' ') //这里也一样,需要先保证i在合法范围,再访问s[i]
            {
                i--;
            }
            
            if(i <= lastend) // i may be -1
            {
                if(!result.empty())
					result.append(" "); // 至少有一个字符串时,需要添加空格
				result.append(s.substr(i+1, lastend - i));
            }
        }
        
		s.assign(result);
    }
};

 

转载于:https://www.cnblogs.com/whyandinside/p/3924392.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值