题目来源: https://leetcode.com/problems/reverse-string/
问题描述: 颠倒一个char数组里面的字符串顺序,只能修改原始数组的值,不允许分配额外的空间。
举例说明:
输入 | 输出 |
---|---|
["h","e","l","l","o"] | ["o","l","l","e","h"] |
["H","a","n","n","a","h"] | ["h","a","n","n","a","H"] |
解决方案
- 遍历数组后用中间变量交换元素位置,时间复杂度Ο(n)
class Solution {
public void reverseString(char[] s) {
int length = s.length;
for(int i=0;i<length;i++) {
if(i < (length-i-1)) {
char temp = s[i];
s[i] = s[length-i-1];
s[length-i-1] = temp;
}
}
}
}
相关文章
暂无评论...