原文题目:
读题:
题目就是将一个字符串进行翻转操作,解法有4种
1)用库函数reverse
2)从后往前进行复制
3)头尾字符进行交换
4)用栈实现
库函数法:
class Solution { public: string reverseString(string s) { reverse(s.begin(),s.end()); return s; } };
复制法:
class Solution { public: string reverseString(string s) { string result; int len = s.length(); int i = len - 1; if(!len) return s; for(;i >= 0;i--) { result += s[i]; } return result; } };
交换法:
class Solution { public: string reverseString(string s) { for(int i = 0, j = s.length() - 1; i < j; i++, j--){ char temp = s[i]; s[i] = s[j]; s[j] = temp; } return s; } };
栈实现:
class Solution { public: string reverseString(string s) { string result ; int len = s.length(); if(len==0) return result; int i = 0; stack<char> stk; while(i< len) { stk.push(s[i]); i++; } while(!stk.empty()) { char temp = stk.top(); result.push_back(temp); stk.pop(); } return result; } };