题目:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
代码:
自己的:
1 class Solution { 2 public: 3 string reverseString(string s) { 4 stack<char> tem; 5 string result; 6 for ( auto c : s) 7 tem.push(c); 8 while (!tem.empty()){ 9 result += tem.top(); 10 tem.pop(); 11 } 12 return result; 13 } 14 };
别人的:
1 class Solution { 2 public: 3 string reverseString(string s) { 4 if (s.size() < 2) 5 return s; 6 int l = 0, r = static_cast<int>(s.size() - 1); 7 while (l < r) 8 { 9 swap(s[l++], s[r--]); 10 } 11 return s; 12 } 13 };
别人的效率好。
swap()函数:交换