• 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.

  • 相关阅读:
    Python3 实现一个简单的TCP 客户端
    Mac 下 安装 和 使用 Go 框架 Beego
    Go 操作文件及文件夹 os.Mkdir及os.MkdirAll两者的区别
    Go gin 之 Air 实现实时加载
    Mac os 配置常用alias
    Mac 下 MAMP配置虚拟主机
    Thinkphp5 项目部署至linux服务器报403错误
    Linux 安装最新版 node.js 之坑
    Mac item2如何使用rz sz 上传下载命令
    Mac 使用 iTerm2 快捷登录远程服务器
  • 原文地址:https://www.cnblogs.com/abc-begin/p/7581820.html
Copyright © 2020-2023  润新知