标签:stack get long ota order ring cas ++ previous
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 的代码
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.
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.
标签:stack get long ota order ring cas ++ previous
原文地址:http://www.cnblogs.com/abc-begin/p/7581820.html