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

2年前 (2022) 程序员胖胖胖虎阿
157 0 0

题目来源: 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;
            }
        }
    }
    
}

版权声明:程序员胖胖胖虎阿 发表于 2022年9月1日 下午6:32。
转载请注明:算法天天练334:字符串翻转 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...