GuilinDev

Lc0344

05 August 2008

344 - Reverse String

原题概述

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

Example:
Given s = [“h”,”e”,”l”,”l”,”o”], return [“o”,”l”,”l”,”e”,”h”].

题意和分析

转换成字符数组,两个索引往中间走,如果相等或者left大于right就停止。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public void reverseString(char[] s) {
        if (s == null || s.length <= 1) {
            return;
        }
        int left = 0;
        int right = s.length - 1;
        while (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}