zoukankan      html  css  js  c++  java
  • LeetCode 541. Reverse String II (反转字符串 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]

    题目标签:String
      今天登陆突然发现LeetCode 有中文版本了- -,再也不用纠结于 如何翻译题目名字了。
     
      题目给了我们一个string s 和 int k,让我们每次在2k 个 chars 里只反转 k 个chars。
      利用Reverse String 里的 two pointers 来反转k 个chars,每一次增加 i by 2*k 就可以了。
      具体请看code。
     
     
     

    Java Solution:

    Runtime beats 67.31% 

    完成日期:04/07/2018

    关键词:two pointers

    关键点:swap left and right chars

     1 class Solution 
     2 {
     3     public String reverseStr(String s, int k) 
     4     {
     5         char [] c_arr  = s.toCharArray();
     6         
     7         for(int i=0; i<c_arr.length; i=i+2*k)
     8         {
     9             int left = i;
    10             int right = Math.min(i + k - 1, c_arr.length - 1); 
    11             
    12             while(left < right)
    13             {
    14                 // swap char
    15                 char temp = c_arr[left];
    16                 c_arr[left] = c_arr[right];
    17                 c_arr[right] = temp;
    18                 
    19                 left++;
    20                 right--;
    21             }
    22             
    23         }
    24         
    25         return new String(c_arr);
    26     }
    27 }

    参考资料:n/a

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    html5 canvas 渐变
    html5 canvas 画直线
    html5在canvas中插入图片
    Window文件夹右击菜单定制
    HTML中解决双击会选中文本的问题
    Linux 下修改mysql 字符集编码
    mysqlimport导入命令使用
    PAM 2500 荧光数据导出数据整合脚本
    Resources for Ecology and Evolution
    Plant Ecology Journal Club, 分享主题和文献列表 825, 2019年春
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/8743544.html
Copyright © 2011-2022 走看看