string反转问题

    xiaoxiao2021-04-17  50

    问题来源:

    点击打开链接

    问题描述:

    Write a function that takes a string as input and returns the string reversed.

    Example: Given s = "hello", return "olleh".

    我的解决方案(2种):

    class Solution { public: string reverseString(string s) { reverse(&s[0],&s[s.size()]); return s; } }; class Solution { public: string reverseString(string s) { string ret; for(int i=0;i<s.size();++i) ret.insert(0,1,s[i]); return ret; } }; 思考:

    前几天做过部分反转string的题,所以这道题做的得心应手,reverse确实很方便,不过一定要记住是传的迭代器进去,另外摘录一个别的swap的做法,也很简单:

    class Solution { public: string reverseString(string s) { int i = 0, j = s.size() - 1; while(i < j){ swap(s[i++], s[j--]); } return s; } };

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

    最新回复(0)