zoukankan      html  css  js  c++  java
  • [leetcode] Reverse String II

    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"
    Restrictions:
    1. The string consists of lower English letters only.
    2. Length of the given string and k will in the range [1, 10000]

     分析:题目比较简单,翻译一下:对一个字符串s,要求每2k个字符中,前k个字符翻转。注意这里如果最后不满足k个字符,那么就翻转全部的剩下字符。
    思路还是很简单的,要调用一个函数来完成翻转的功能。具体代码如下:
     1 class Solution {
     2     public String reverseStr(String s, int k) {
     3         char[] array = s.toCharArray();
     4         for ( int i = 0 ; i < s.length() ; i +=  2*k ){
     5             reverse(array,i,i+k-1);
     6         }
     7         return String.valueOf(array);
     8     }
     9 
    10     private void reverse(char[] array, int start, int end) {
    11         if ( start > array.length ) return;
    12         int low = start;
    13         int high = Math.min(end,array.length-1);
    14         while ( low < high ){
    15             char c = array[low];
    16             array[low] = array[high];
    17             array[high] = c;
    18             low++;
    19             high--;
    20         }
    21     }
    22 }

          运行时间3ms,击败100%的提交。

          这里可以总结一下字符串翻转的小技巧,就是用两个指针来完成。

  • 相关阅读:
    Linux 目录结构
    date命令--修改linux系统时间
    uniq linux下去除重复行命令
    Linux查看程序端口占用情况
    openfire连接登陆优化方案
    hdu 4848 搜索+剪枝 2014西安邀请赛
    经常使用ARM汇编指令
    一维DFT
    C++ lambda 表达式传递的变量默认不可变
    wm命令用法及LCD显示图标大小不正常时解决的方法
  • 原文地址:https://www.cnblogs.com/boris1221/p/9316974.html
Copyright © 2011-2022 走看看