Leetcode#344. Reverse String

0人阅读 评论(0) 收藏 举报
分类:

题目描述:字符串逆序

使用栈的解法:

class Solution {
public:
    string reverseString(string s) 
    {
        if(s.empty())
            return s;
        stack<char> sta;
        for(int i = 0; i < s.length(); ++i)
            sta.push(s[i]);
        s = "";
        while(!sta.empty())
        {
            s += sta.top();
            sta.pop();
        }
        return s;
    }
};

一个空间复杂度为O(1)的解法:

class Solution {
public:
    string reverseString(string s) 
    {
        int left = 0, right = s.length() - 1;
        while(left < right)
        {
            swap(s[left ++], s[right --]);
        }
        return s;
    }
};

超简单的解法:直接调用 reverse()

class Solution {
public:
    string reverseString(string s) 
    {
        reverse(s.begin(), s.end());
        return s;
    }
};
查看评论

String类

-
  • 1970年01月01日 08:00

leetcode_344 Reverse String

题目分析:对于给定的字符串,执行逆转操作。 解题思路:先统计字符串的长度,然后遍历字符串,将字符串的前后元素一一对调即可实现。 实现程序C++版本class Solution { public: ...
  • yzhang6_10
  • yzhang6_10
  • 2016-05-08 18:45:02
  • 1565

344. Reverse String [easy] (Python)

题目链接https://leetcode.com/problems/reverse-string/题目原文 Write a function that takes a string as inpu...
  • coder_orz
  • coder_orz
  • 2016-05-07 14:42:48
  • 2018

【LeetCode】Reverse Words in a String III 解题报告

【LeetCode】Reverse Words in a String III 解题报告标签(空格分隔): LeetCode题目地址:https://leetcode.com/problems/rev...
  • fuxuemingzhu
  • fuxuemingzhu
  • 2017-04-12 11:48:48
  • 1212

(LeetCode) Reverse Words in a String

problem :Reverse Words in a String Given an input string, reverse the string word by ...
  • zhangyuehuan
  • zhangyuehuan
  • 2014-04-13 09:26:54
  • 8272

[leetcode] 151. Reverse Words in a String 解题报告

题目链接:https://leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reverse the s...
  • qq508618087
  • qq508618087
  • 2016-01-18 14:40:11
  • 1739

【LeetCode刷题Java版】Reverse Words in a String

Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", r...
  • bruce_6
  • bruce_6
  • 2014-10-13 14:21:21
  • 2172

reverse a string反转字符串

题目写出一个函数,实现输入一个字符串,返回一个反置字符串。解题过程1.首先考虑用栈的数据结构实现反置。 2.查找java中的栈的结构用法 栈的类Stack没有相应的转置方法。所以放弃使用类 3....
  • fegnkuang
  • fegnkuang
  • 2016-05-01 05:44:16
  • 2154

Java 原串翻转(5 Ways To Reverse A String In Java )

java原字符串翻转
  • momoddddddd
  • momoddddddd
  • 2016-02-09 20:27:21
  • 1151

【LeetCode】345. Reverse Vowels of a String 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51416284Subject 出处:https://leetcode.com/pro...
  • crazy1235
  • crazy1235
  • 2016-05-16 23:57:49
  • 6986
    个人资料
    持之以恒
    等级:
    访问量: 3万+
    积分: 2156
    排名: 2万+