Problem Description
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: [“h”,“e”,“l”,“l”,“o”]
Output: [“o”,“l”,“l”,“e”,“h”]
Example 2:
Input: [“H”,“a”,“n”,“n”,“a”,“h”]
Output: [“h”,“a”,“n”,“n”,“a”,“H”]
Solution
这道题是在不创建新的数组空间的前提下反转字符数组。开始没仔细看题目就习惯性建空数组暴力解法了orz
思路很简单,以中间为分界线,左右调换,用一个temp
保存中间值。分奇偶讨论 終わり
(总感觉有点啰嗦但想不出什么更简练的办法了就这样吧
class Solution {
public:
void reverseString(vector<char>& s) {
int n = s.size();
if(n%2 == 0){
int k=1;
for(int i=n/2-1; i>=0; i--){
char temp = s[i];
s[i] = s[i+k];
s[i+k] = temp;
k += 2;
}
}else {
int k=2;
for(int i=floor(n/2)-1; i>=0; i--){
char temp = s[i];
s[i] = s[i+k];
s[i+k] = temp;
k +=2;
}
}
}
};
突然想到还有一种,可以从中间延伸出去也可以从外往里进行swap操作啊 空间复杂度 O ( 1 ) O(1) O(1)
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0;
int right = s.size()-1;
while(left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left += 1;
right -= 1;
}
}
};