close

Hi,身為C++的初學者,練習各種題目是必經之路,在讓我們來練習一個關於陣列的題目吧。


[題目]

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

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


[小弟的解法]

class Solution {
public:
    string reverseString(string s) {
      1    string Rlt;
      2    int len,i;
      3    if(s=="") return(Rlt);
      4    len=s.length();
      5    for(i=len-1; i>=0; i--) Rlt+=s[i]; 
      6    return(Rlt);
    }
};


[使用技巧]

1. line4: s.length()   結取該字串的長度。

2. line5: len-1  是為了避掉結束字元'/0';


[心得]

這個題目主要在考array的觀念,對於初心者來說,練習這道題目可以增加對自己的信心,讓自己覺得好像可以做點什麼的感覺。

希望有其他解法的朋友可以一起分享不同的解法,共同精進C++的功力。


[題目來源]

https://leetcode.com/problems/reverse-string/

arrow
arrow

    SouthOcean929 發表在 痞客邦 留言(0) 人氣()