解法一:
开辟一个和str长度大小相同的一个字符串ans,把传入的str倒序赋值到ans字符串上, 时间复杂度,额外空间复杂度
c++
class Solution { public: string solve(string str) { string ans = str; int len = str.length(); for(int i = 0 ; i < len ;i++) { ans[i] = str[len-1-i]; } return ans; } };
java
import java.util.*; public class Solution { public String solve (String str) { char[] ans = str.toCharArray(); int len = str.length(); for(int i = 0 ; i < len ;i++) { ans[i] = str.charAt(len-1-i); } return new String(ans); } }
python
class Solution: def solve(self , str ): ans="" Len = len(str) for i in range(0,Len): ans+=str[Len-1-i] return ans
解法二:
原地交换,,注意:交换进行的次数是次
时间复杂度,额外空间复杂度
class Solution { public: string solve(string str) { int len = str.length(); for(int i = 0 ; i < len/2 ;i++) { swap(str[i],str[len-1-i]); } return str; } };
java
import java.util.*; public class Solution { public String solve (String str) { char[] cstr = str.toCharArray(); int len = str.length(); for(int i = 0 ; i < len/2 ;i++) { char t = cstr[i]; cstr[i] = cstr[len-1-i]; cstr[len-1-i]=t; } return new String(cstr); } }
解法三:
直接调用库函数
c++
class Solution { public: string solve(string str) { reverse(str.begin(),str.end()); return str; } };
java
import java.util.*; public class Solution { public String solve (String str) { StringBuffer sb =new StringBuffer(str);//此方法针对的是io流,不能针对字符串。 return sb.reverse().toString(); } }
python
class Solution: def solve(self , str ): return str[::-1]