关闭

[leetcode] 344. Reverse String

标签: leetcodeeasy
86人阅读 评论(0) 收藏 举报
分类:

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>


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9738次
    • 积分:632
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:150篇
    • 译文:0篇
    • 评论:0条
    文章分类