本文共 830 字,大约阅读时间需要 2 分钟。
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:
Input: [“h”,“e”,“l”,“l”,“o”]
Output: [“o”,“l”,“l”,“e”,“h”]
典型的双指针题~
class Solution { public char[] reverseString(char[] s) { if(s.length <= 0 || s == null) return null; if(s.length == 1) return s; int head = 0, tail = s.length - 1; while(head <= tail){ char temp = s[tail]; s[tail] = s[head]; s[head] = temp; head++; tail--; } return s; }}
这道题没啥好说的,如果现实中真的需要反转的话,直接用StringBuilder
中的reverse()
方法吧
转载地址:http://vfqvb.baihongyu.com/