0%

June Leetcoding Challenge(6.4)

Reverse String

  1. Write a function that reverses a string. The input string is given as an array of characters char[].

    Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

    You may assume all the characters consist of printable ascii characters.

Example 1:

1
2
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

1
2
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

思路:

设置两个指针,一个指针指向首元素l,另一个指针指向末尾元素r,开始进行while循环,循环推出条件为l<r。 通过移动l,r两个指针交换元素。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public void reverseString(char[] s) {
int l = 0;
int r = s.length-1;
while(l<r){
char tmp = s[r];
s[r] = s[l];
s[l] =tmp;
l++;
r--;
}
}
}
-------------本文结束感谢您的阅读-------------

本文标题:June Leetcoding Challenge(6.4)

文章作者:Jungle

发布时间:2020年06月04日 - 08:21

最后更新:2020年06月04日 - 08:23

原始链接:http://yoursite.com/2020/06/04/LeetCodeJune4th/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Welcome to my other publishing channels