算法天天练334:字符串翻转

题目来源: 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"]

解决方案

  1. 遍历数组后用中间变量交换元素位置,时间复杂度Ο(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;
            }
        }
    }
    
}

posted @ 2019-10-16 11:32  编码专家  阅读(445)  评论(0编辑  收藏  举报