温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中怎么利用LeetCode翻转字符串中的单词

发布时间:2021-08-04 17:52:54 来源:亿速云 阅读:169 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关C++中怎么利用LeetCode翻转字符串中的单词,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

[LeetCode] 557.Reverse Words in a String III 翻转字符串中的单词之三

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

这道题让我们翻转字符串中的每个单词,感觉整体难度要比之前两道Reverse Words in a String II和Reverse Words in a String要小一些,由于题目中说明了没有多余空格,使得难度进一步的降低了。首先我们来看使用字符流处理类stringstream来做的方法,相当简单,就是按顺序读入每个单词进行翻转即可,参见代码如下:

解法一:

class Solution {
public:
    string reverseWords(string s) {
        string res = "", t = "";
        istringstream is(s);
        while (is >> t) {
            reverse(t.begin(), t.end());
            res += t + " ";
        }
        res.pop_back();
        return res;
    }
};

下面我们来看不使用字符流处理类,也不使用STL内置的reverse函数的方法,那么就是用两个指针,分别指向每个单词的开头和结尾位置,确定了单词的首尾位置后,再用两个指针对单词进行首尾交换即可,有点像验证回文字符串的方法,参见代码如下:

解法二:

class Solution {
public:
    string reverseWords(string s) {
        int start = 0, end = 0, n = s.size();
        while (start < n && end < n) {
            while (end < n && s[end] != ' ') ++end;
            for (int i = start, j = end - 1; i < j; ++i, --j) {
                swap(s[i], s[j]);
            }
            start = ++end;
        }
        return s;
    }
};

关于C++中怎么利用LeetCode翻转字符串中的单词就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI