剑指offer-翻转单词顺序列

    xiaoxiao2022-07-02  105

    38.翻转单词顺序列

    题目内容:

    代码及思路:

    1.先翻转句子;2.再翻转每个单词

    #include<iostream> #include<string> using namespace std; class Solution { public: void Reverse_core(string& str, int begin, int end) { if (begin > end) return; while (begin <end) { char temp = str[begin]; str[begin] = str[end]; str[end] = temp; begin++; end--; } } string Reverse(string& str) { if (str.length() == 0) return ""; int length = str.length(); int begin = 0; int end = length - 1; Reverse_core(str, begin, end);//对整个句子进行翻转 int index = 0; for (int i = 0; i < length; i++) { //对每个单词进行单独的翻转 if (str[i] == ' ' || str[i] == '\0') { Reverse_core(str, index, i - 1); index = i + 1; } } return str; } }; void main() { Solution* object = new Solution; string str; getline(cin, str); str = object->Reverse(str); cout << str << endl; }

     

    最新回复(0)