字符串——字符串反转

xiaoxiao2021-02-28  71

一、要求

请编写一个函数,其功能是将输入的字符串反转过来。

示例:

输入:s = "hello" 返回:"olleh"

二、方案

想法:

字符串反转,从两头往中间走,即第一个字母和最后一个交换,第二个和倒数第二个,且最关键的一点是,字符串中的字符保存到数组中后,数组中第一个字母和最后一个字母的下标和为array.size()-1,数组中第二个字母和倒数第二个的下标和同样也为array.size()-1,于是:

做法一:

class Solution { public: string reverseString(string s) { char temp; for(int i=0; i<s.size()/2; i++){ temp = s[i]; s[i] = s[s.size()-(i+1)]; s[s.size()-(i+1)] = temp; } return s; } };

做法二:

从两头往中间走还有不同的走法

class Solution { public: string reverseString(string s) { int left = 0, right = s.size() - 1; while (left < right) { char t = s[left]; s[left++] = s[right]; s[right--] = t; } return s; } };

做法三:

直接调用string类库中已经封装好的swap()函数

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

我又在vs中写了一下试试:

include<string> include<iostream> using namespace std; string reverseString(string s){ int left = 0; int right = s.size() - 1; while (left < right) { swap(s[left++], s[right--]); } return s; } int main(){ cout<<reverseString("Hello"); return 0; }

注:我之前是不知道string类型的操作[ ]用来存取单一字符,现在就可以把字符串类似于数组使用

字符串反转还有很多做法 可参考别人的博客~

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

最新回复(0)