zoukankan      html  css  js  c++  java
  • 344. Reverse String【easy】

    344. Reverse String【easy】

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

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

    解法一:

     1 class Solution {
     2 public:
     3     string reverseString(string s) {
     4         int start = 0, end = s.length() - 1;
     5         
     6         while (start <= end) {
     7             char c = s[start];
     8             s[start] = s[end];
     9             s[end] = c;
    10             ++start;
    11             --end;
    12         }
    13         
    14         return s;
    15     }
    16 };

    解法二:

     1 class Solution {
     2 public:
     3     void reverseStringHelper(string & s, int len, int start, string & result)
     4     {
     5         if (start == len) {
     6             return;
     7         }
     8         
     9         reverseStringHelper(s, len, start + 1, result);
    10         
    11         result += s[start];
    12     }
    13     
    14     string reverseString(string s) {
    15         string result;
    16         
    17         reverseStringHelper(s, s.length(), 0, result);
    18         
    19         return result;
    20     }
    21 };

    递归

    解法三:

    1 public class Solution {
    2     public String reverseString(String s) {
    3         int length = s.length();
    4         if (length <= 1) return s;
    5         String leftStr = s.substring(0, length / 2);
    6         String rightStr = s.substring(length / 2, length);
    7         return reverseString(rightStr) + reverseString(leftStr);
    8     }
    9 }

    参考@ratchapong.t 的代码

    Complexity Analysis

    Time Complexity: `O(n log(n))` (Average Case) and `O(n * log(n))` (Worst Case) where `n` is the total number character in the input string. The recurrence equation is `T(n) = 2 * T(n/2) + O(n)`. `O(n)` is due to the fact that concatenation function takes linear time. The recurrence equation can be solved to get `O(n * log(n))`.

    Auxiliary Space: `O(h)` space is used where `h` is the depth of recursion tree generated which is `log(n)`. Space is needed for activation stack during recursion calls.

    Algorithm

    Approach: Divide and Conquer (Recursive)

    The string is split into half. Each substring will be further divided. This process continues until the string can no longer be divided (length `<= 1`). The conquering process will take they previously split strings and concatenate them in reverse order.

  • 相关阅读:
    Leetcode_02【两数相加】——【难度:中】
    Leetcode_39【组合总和】
    Leetcode_38【报数】
    Leetcode_36【有效的数独】
    Leetcode_35【搜索插入位置】
    51nod1347 旋转字符串
    WebH
    ExcelHelper
    文件二进制与String相互转换
    汇编语言里 eax, ebx, ecx, edx, esi, edi, ebp, esp
  • 原文地址:https://www.cnblogs.com/abc-begin/p/7581820.html
Copyright © 2011-2022 走看看