[leetcode] 344. Reverse String

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "oleo".

Solution

Idea: swap characters

<span style="font-size:14px;">class Solution {
public:
    string reverseString(string s) {
        for(int i=0; i<floor(s.size()/2); i++){
            int j = s.size() - i - 1;
            char ctemp = s[j];
            s[j] = s[i];
            s[i] = ctemp;
        }
        return s;
    }
};</span>

Solution

Idea: rearrange string by inverse order

<span style="font-size:14px;">class Solution {
public:
    string reverseString(string s) {
        int len = s.length();
        string ss = "";
        for (int i=0; i<len; i++)
            ss += s[len-i-1];
        return ss;
    }
};</span>


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/denny851108/article/details/51542582
文章标签: leetcode easy
个人分类: leetcode
上一篇[leetcode] 169. Majority Element
下一篇[leetcode] 350. Intersection of Two Arrays II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭