zoukankan      html  css  js  c++  java
  • Reverse String

    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 lessthan 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 asoriginal.

    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]
     1 public class Solution {
     2     public String reverseStr(String s, int k) {
     3         int n = s.length();
     4         StringBuilder result = new StringBuilder();
     5         
     6         for (int i = 0; i < n; ) {
     7             if (i + k > n) {
     8                 // less than k chars left, reverse all
     9                 result.append(reverseStr(s, i, n - 1));
    10                 break;
    11             } else if (i + k <= n && i + 2 * k > n) {
    12                 // k ~ 2k, reverse the first k chars, left the remaining as the same
    13                 result.append(reverseStr(s, i, i + k - 1));
    14                 result.append(s.substring(i + k));
    15                 break;
    16             } else if (i + 2 * k <= n) {
    17                 // more than 2k chars left, reverse the first k chars
    18                 result.append(reverseStr(s, i, i + k - 1));
    19                 result.append(s.substring(i + k, i + 2 * k));
    20                 i += 2 * k;
    21             } 
    22         }
    23         return result.toString();
    24     }
    25     
    26     private StringBuilder reverseStr(String s, int begin, int end) {
    27         StringBuilder result = new StringBuilder();
    28         while (end >= begin) {
    29             result.append(s.charAt(end--));
    30         }
    31         return result;
    32     }
    33 }
     
  • 相关阅读:
    PTA 1022 Digital Library (30分) 坑多需谨慎!!!
    PAT 1013 Battle Over Cities (25分) 图的连通分量+DFS
    PAT 1021 Deepest Root (25分) 从测试点3超时到满分再到代码优化
    Java面向对象-------多态总结
    C后端设计开发
    C后端设计开发
    C后端设计开发
    C后端设计开发
    C后端设计开发
    一个真正的客户端非阻塞的 connect
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6597789.html
Copyright © 2011-2022 走看看