zoukankan      html  css  js  c++  java
  • 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++:

    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:

    方法一:

    class Solution(object):
        def reverseString(self, s):
            """
            :type s: str
            :rtype: str
            """
            return s[::-1]
    

    方法二:

    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:

    /**
     * @param {string} s
     * @return {string}
     */
    var reverseString = function(s) {
        return s.split('').reverse().join('');
    };
    

      

      

  • 相关阅读:
    第十三周学习进度
    第二次冲刺阶段每日任务02
    第二次冲刺阶段每日任务01
    构建之法阅读笔记03
    找水王续
    第十二周学习进度
    找水王
    第十一周学习进度
    博客园的用户体验
    找水王1
  • 原文地址:https://www.cnblogs.com/breezeljm/p/5734917.html
Copyright © 2011-2022 走看看