注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
Java1:
public class Solution {
public String reverseString(String s) {
char[] word = s.toCharArray();
int i = 0;
int j = s.length() - 1;
while (i < j) {
char temp = word[i];
word[i] = word[j];
word[j] = temp;
i++;
j--;
}
return new String(word);
}
}
Java2:
public class Solution {
public String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
}
完整cpp程序:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
class Solution {
public:
string reverseString(string s) {
int i = 0;
int j = s.size() - 1;
while (i < j)
swap(s[i++], s[j--]);
return s;
}
};
int main() {
string str;
getline(cin, str);
Solution sol;
cout << sol.reverseString(str);
return 0;
}