zoukankan      html  css  js  c++  java
  • 541. Reverse String II 指定翻转前k个的字符串

    [抄题]:

    Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

    Example:

    Input: s = "abcdefg", k = 2
    Output: "bacdfeg"

     [暴力解法]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    不知道怎么写复杂的swap:原来是用的封装

    [一句话思路]:

    特殊情况比较重要:每2k翻转一次,n<k时直接就翻转n了

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    /**
         * 0            k           2k          3k
         * |-----------|-----------|-----------|---
         * +--reverse--+           +--reverse--+
         */

    [一刷]:

    1. 第n位是n - 1,不是i + n - 1,怎么会出这种错呢
    2. swap中有while循环,要一直进行,最好写成l r,这都不会说明基础太差

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    不知道怎么写复杂的swap:原来是用的封装

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    swap函数

     public void swap(char[] words, int i, int j) {
            while (i < j) {
                char temp = words[i];
                words[i] = words[j];
                words[j] = temp;
            
                i++;
                j--;
            }
        }

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public String reverseStr(String s, int k) {
            //corner case
            if (s == null) {
                return null;
            }
            if (k == 0) {
                return s;
            }
            //convert
            char[] words = s.toCharArray();
            int i = 0;
            int n = s.length();
            //while (i < n)
            while (i < n) {
            //define j
                int j = Math.min(i + k - 1, n - 1);
                swap(words, i, j);
            //i += 2k;
                i += 2 * k;
            }
            //return
            return new String(words);
        }
        
        public void swap(char[] words, int i, int j) {
            while (i < j) {
                char temp = words[i];
                words[i] = words[j];
                words[j] = temp;
            
                i++;
                j--;
            }
        }
    }
    View Code
  • 相关阅读:
    float转varchar
    我的优化经验:内链是SEO的基础
    转:2008年微软Windows硬件工程(WinHEC)大会
    sql语句去掉前面的0(前导零,零前缀)
    去掉ID重复的数据
    蛙蛙推荐:蛙蛙牌firefox插件
    每日阅读20081127
    网赚经验之谈:成为高手之路
    (chinaz)巧妙选购付费链接
    把某个表的数据导出成insert语句(数据导出 insert语句)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8594599.html
Copyright © 2011-2022 走看看