LeetCode 344. Reverse String

https://leetcode.com/problems/reverse-string/description/

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

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

  • 字符串简单处理题,可以使用STL算法reverse把整串反转,或者string的swap逐个交换
  • 注意空串""的情况
  • LeetCode 344. Reverse String

 1 //
 2 //  main.cpp
 3 //  LeetCode
 4 //
 5 //  Created by Hao on 2017/3/16.
 6 //  Copyright © 2017年 Hao. All rights reserved.
 7 //
 8 
 9 #include <iostream>
10 #include <vector>
11 using namespace std;
12 
13 class Solution {
14 public:
15     // reverse
16     string reverseString(string s) {
17         string sr = s;
18         
19         reverse(sr.begin(), sr.end());
20         
21         return sr;
22     }
23     
24     // swap
25     string reverseString2(string s) {
26         for (int i = 0; i < s.size() / 2; i ++)
27             swap(s.at(i), s.at(s.size() - 1 - i));
28         
29         return s;
30     }
31 };
32 
33 int main(int argc, char* argv[])
34 {
35     Solution    testSolution;
36     
37     vector<string> strs {"", "hello", "a.b,."};
38 
39     /*
40      ""
41      "olleh"
42      ".,b.a"
43      */
44     for (auto s : strs) {
45         cout << "\"" << testSolution.reverseString(s) << "\"" << endl;
46         cout << "\"" << testSolution.reverseString2(s) << "\"" << endl;
47     }
48     
49     return 0;
50 }
View Code

 

posted on 2018-02-02 15:37  浩然119  阅读(155)  评论(0编辑  收藏  举报