2020-4-16 第一次 難度:簡(jiǎn)單
核心要求:不使用額外的空間父虑,原地修改數(shù)組,O(1)的空間復(fù)雜度
c++代碼
法1:
#include<string>
#include<algorithm>
class Solution {
public:
void reverseString(vector<char>& s) {
reverse(s.begin(),s.end());
}
};
c++法2:
class Solution {
public:
void reverseString(vector<char>& s) {
int len = s.size();
for(int i=0;i<len/2;i++)
{
if(s[i]==s[len-1-i]) continue;
char temp =s[i];
s[i]=s[len-1-i];
s[len-1-i]=temp;
}
}
};
Python代碼
雙指針?lè)ǎ?/p>
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
i,j = 0,len(s)-1
while i<j:
s[i],s[j]=s[j],s[i]
i+=1
j-=1
一步法:
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]
遞歸+雙指針?lè)ǎ?/p>
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# double pointer and recursion
def recur_(s, i,j):
if i>=j:
return
else:
s[i],s[j] = s[j],s[i]
recur_(s,i+1,j-1)
recur_(s,0,len(s)-1)
python代碼參考:反轉(zhuǎn)字符串