编写一个函数,其作用是将输入的字符串反转过来。
示例 1:
输入: "hello" 输出: "olleh"
示例 2:
输入: "A man, a plan, a canal: Panama" 输出: "amanaP :lanac a ,nalp a ,nam A"
C++解法
class Solution {
public:
string reverseString(string s) {
int left = 0, right = s.size() - 1;
while (left < right) {
char t = s[left];
s[left++] = s[right];
s[right--] = t;
}
return s;
}
};
java解法
class Solution {
public String reverseString(String s) {
int length =s.length();
char[] str=s.toCharArray();
for(int i=0;i<length/2;i++){
char temp =str[i];
str[i]=str[length-1-i];
str[length-1-i]=temp;
}
return new String(str);
}
}