344. Reverse String(Java/C++)

来源:互联网 发布:淘宝网最新版本 编辑:程序博客网 时间:2024/06/15 08:49

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;}
原创粉丝点击