反转单词顺序

    xiaoxiao2021-03-26  35

    反转单词顺序


    题源:https://leetcode.com/problems/reverse-words-in-a-string/leetcode 151

    思路

    先每个单词反转最后整个数组反转由于字符串开头和结尾和中间会有多个空格,所以需要考虑去掉多余的空格

    代码

    void reverseword(string &s, int start, int end){ if (start>=end) { return; } else{ while (start<end) { char temp = s[start]; s[start++] = s[end]; s[end--] = temp; } return; } } void reverseWords(string &s) { int i=0, j=0; int l=0; int len = s.length(); int wordcount = 0; while (true) { while (s[i]==' '&&i<len) {i++;} if (i==len) {break;} if (wordcount) {s[j++]=' ';} //当是第一个单词时前面不需要加空格,而后续的单词前面需要加上一个空格 l = j; while (s[i]!=' '&&i<len) {s[j++] = s[i++];} //旋转一个单词 reverseword(s,l,j-1); wordcount++; } s.resize(j); //一定需要改变string对象s的大小,原因见下面 reverseword(s,0,j-1); //整体旋转数组 }

    需要resize字符串的大小的原因:

    因为当不改变字符串的大小的话:当输入:” hello world “时,会得到如下第二行的答案:

    当使用resize改变string的大小后:

    resize的用法:http://www.howsoftworks.net/cplusplus.api/std/string_resize.html

    转载请注明原文地址: https://ju.6miu.com/read-662085.html

    最新回复(0)