LeetCode刷题:344.Reverse String


344. Reverse String

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

Example 1:

Input: “hello”

Output: “olleh”

Example 2:

Input: “A man, a plan, a canal: Panama”

Output: “amanaP :lanac a ,nalp a ,nam A”

解题思路:
  • 思路1: 通过s.length()获取s的字符长度,然后通过下标访问s,将s中的字符从尾到头拼接到result上,得到返回结果。
  • 思路2: 利用reverse函数,reverse(beg, end)会将区间(beg, end)之间的元素全部逆转。
    解答:
    // code 1: 
    // 4ms
    class Solution {
    public:
      string reverseString(string s) {
          string result = "";
          auto len = s.length();
          while(len > 0)
          {
              result += s[len - 1];
              --len;
          }
          return result;
      }
    };
    // code 2:
    // 4ms
    class Solution {
    public:
      string reverseString(string s) {
          reverse(s.begin(),s.end());
          return s;
      }
    };

文章作者: Jason
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Jason !
  目录