leetcode 344. Reverse String 字符串逆序处理

傷城~ 2022-06-07 01:15 225阅读 0赞

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

Example:
Given s = “hello”, return “olleh”.

这道题直接反转字符串即可,Java中使用StringBuilder即可。

建议和这一道题一起学习leetcode 541. Reverse String II 反转字符串

代码如下:

  1. /*
  2. * 只用StringBilder更好
  3. * */
  4. class Solution
  5. {
  6. public String reverseString(String s)
  7. {
  8. return new StringBuilder(s).reverse().toString();
  9. }
  10. }

下面是C++的做法,就是直接做逆序就可以了

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. using namespace std;
  19. class Solution
  20. {
  21. public:
  22. string reverseString(string s)
  23. {
  24. reverse(s.begin(), s.end());
  25. return s;
  26. }
  27. };

发表评论

表情:
评论列表 (有 0 条评论,225人围观)

还没有评论,来说两句吧...

相关阅读