Reverse string

来源:互联网 发布:麦星投资 知乎 编辑:程序博客网 时间:2024/06/17 05:55

问题描述

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

Example:
Given s = “hello”, return “olleh”.

问题分析

维护两个下表指针i,j,从字符串的两边向中间遍历,当i小于j时交换位置,并且让i加一,j减一。

算法(C++)

class Solution {public:    string reverseString(string s) {        int i = 0;        int j = s.size() - 1;        char temp;        while(i < j)        {            temp = s[i];            s[i] = s[j];            s[j] = temp;            i++;            j--;        }    }};

总结

对字符串操作往往是对下标操作的考察,也有很多问题会使用维护两个指针的方法,虽然不难,但这种方法应该是更为简单的。