Reverse Words in a String III(leetcode)

来源:互联网 发布:最好的大数据上市公司 编辑:程序博客网 时间:2024/05/17 21:50

Reverse Words in a String III

  • Reverse Words in a String III
    • 题目
    • 解析
    • 解决


题目

leetcode题目

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving white space 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.


解析

题目需要我们做的事情是将给定字符串中的单词前后颠倒,而单词本身在字符串的位置以及字符串中的空格位置不变。
Example 1中,给定的字符串为Let's take LeetCode contest,则我们以空格为分界,将字符串分成Let'stakeLeetCodecontest4个子字符串,再分别对其前后颠倒,以实现题目要求。


解决

class Solution {public:    string reverseWords(string s) {        string result, temp;        int subpos = 0;        int sublen = 0;        int len = s.length();        for (int i = 0; i < len; i++) {            if (s[i] == ' ') {                result += reverse(s.substr(subpos, sublen)) + ' ';                subpos = i + 1;                sublen = 0;            } else if (i == len - 1){                result += reverse(s.substr(subpos, sublen + 1));            } else {                sublen++;            }        }        return result;    }    string reverse(string s) { // 对子字符串进行颠倒        string result;        int len = s.length();        for (int i = len - 1; i > -1; i--) {            result += s[i];        }        return result;    }};
原创粉丝点击