题目
描述
写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)
数据范围: 0≤n≤1000
要求:空间复杂度 O(n),时间复杂度 O(n)
思路
这个题太简单了,python的话步幅倒着走就行,c++用栈的特点进行存储然后放出来就行。
代码
python版本:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 反转字符串
# @param str string字符串
# @return string字符串
#
class Solution:
def solve(self , str: str) -> str:
# write code here
if not str:
return str
return str[::-1]
c++版本:
class Solution {
public:
/**
* 反转字符串
* @param str string字符串
* @return string字符串
*/
string solve(string str) {
// write code here
if(str.size()==0){
return str;
}
stack<char> st;
string s="";
for(int i=0; i<str.size();i++){
st.push(str[i]);
}
while(!st.empty()){
s += st.top();
st.pop();
}
return s;
}
};