LeetCode刷题笔记(Reverse String)

今天趁着编程的热情还在,又找了一道不难的题刷了下,感觉还好。

具体题目如下:

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

Example 1:

Input: "hello"
Output: "olleh"
Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

 

题意分析:

给定一个字符串,将其进行翻转。

解答如下:

方法一(对撞指针法)

用两个指针分别指向字符串的左右两端,让它们齐头并进的同时并交换对应位置的元素,进而达到对字符串进行翻转的目的。

class Solution {
public:
    string reverseString(string s) {
        int l = 0;
        int r = (int)s.size()-1;
        while( l < r ){
            swap(s[l++],s[r--]);
      }
        return s;//返回函数一定是在对应函数内部
    }

};

提交后的结果如下:

LeetCode刷题笔记(Reverse String) 

日积月累,与君共进,增增小结,未完待续。