zoukankan      html  css  js  c++  java
  • Reverse String

    Leetcode 344. Reverse String

    题目网址:https://leetcode.com/problems/reverse-string/

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

    Example:

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

     

    解法:

    C++:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Solution {
    public:
        string reverseString(string s) {
            int len = s.length();
            char result = '';
            int j = 0;
            for(int i = len-1;i>=0;i--) {
                result[j] = s[i];
                j++;
            }
            return result;
        }
    };

    Python:

    方法一:

    1
    2
    3
    4
    5
    6
    7
    class Solution(object):
        def reverseString(self, s):
            """
            :type s: str
            :rtype: str
            """
            return s[::-1]

    方法二:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class Solution(object):
        def reverseString(self, s):
            """
            :type s: str
            :rtype: str
            """
            t = list(s)
            l = len(t)
            for i,j in zip(range(l-1, 0, -1), range(l//2)):
                t[i], t[j] = t[j], t[i]
            return "".join(t)

      

    Javascript:

    1
    2
    3
    4
    5
    6
    7
    /**
     * @param {string} s
     * @return {string}
     */
    var reverseString = function(s) {
        return s.split('').reverse().join('');
    };

      

      

     

     

     

    分类: Leetcode

  • 相关阅读:
    置顶功能改进
    Skin设计小组新作品发布—绿草蓝天
    代码着色功能改进
    增加了将文章收藏至网摘的功能
    [公告]C++博客开通
    [新功能]显示文章所属分类
    新Skin发布
    北京.NET俱乐部活动公告
    正式开始学习.NET 2.0
    关于共同学习.NET 2.0的想法
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/5735018.html
Copyright © 2011-2022 走看看