Leetcode - String - 344. Reverse String (3種寫法)

1. Problem Description

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

 

Example:

Given s = "hello", return "olleh".

反轉字符串

2. My solution1(另開闢字符串存儲)

class Solution {
public:
    string reverseString(string s) {
         int len=s.length();
         string res=s;
         for(int i=0;i<len;i++)
            res[len-1-i]=s[i];
         return res;
    }
};


3. My solution2(逐個交換頭尾) 

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

4. My solution3 (用棧實現)

順序壓入,逆序彈出。

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章