LeetCode - Reverse String
2016-04-22 23:11
357 查看
Question
Link : 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”.
Code
哈哈,第一个最狗血的版本就是调用接口直接逆序字符串了。(C++ : 12ms)class Solution { public: string reverseString(string s) { reverse(s.begin(), s.end()); return s; } };
但这肯定不是这题的存在的意义所在么。。
本着学习的思路我们还是可以用多几种方式实现的么。。
所以就来了第二种思路。(C++ : 12ms)
class Solution { public: string reverseString(string s) { string res; for(int i = s.size() - 1; i >= 0; i--) res += s[i]; return res; } };
上面的版本可能需要额外的空间复杂度,所以我们想着能不能直接就在原字符串上操作。所以有了这个版本。(C++ : 12ms)
class Solution { public: string reverseString(string s) { char ch; int len = s.size(); int hlen = len / 2; for(int i = 0; i < hlen; i++){ ch = s[i]; s[i] = s[len - i - 1]; s[len - i - 1] = ch; } return s; } }; //同一种思路的实现 class Solution { public: string reverseString(string s) { int i = 0, j = s.size() - 1; while(i < j){ swap(s[i++], s[j--]); } return s; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解