zoukankan      html  css  js  c++  java
  • 字符串问题:去掉字符串中连续出现 k 个 0 的子串

    题目

      给定一个字符串 str 和 一个整数 k, 如果 str 中正好有连续 k 个 ‘0’ 字符出现时,把 k 个连续的 ‘0’ 字符去除,返回处理后的字符串。

    举例

      str="A00B", k=2, 返回 “A  B”

      str="A0000B000", k=3, 返回 “A0000B”

    难度

      一星

    解答

     1 public class Main {
     2 
     3     public static void main(String[] args) {
     4         System.out.println(new Main().removeKZeros("A00B", 2));//A  B
     5         System.out.println(new Main().removeKZeros("A0000B000", 3));//A0000B
     6     }
     7     
     8     public String removeKZeros(String str, int k){
     9         if(str == null || k < 1) return str;
    10         char[] chs = str.toCharArray();
    11         int count = 0;  //统计连续出现字符'0'的次数
    12         int start = -1; //记录开始出现字符'0'的位置
    13         for(int i = 0, len = chs.length; i < len; i++){
    14             char ch = chs[i];
    15             if(ch == '0'){
    16                 count++;
    17                 start = start == -1 ? i : start;
    18             }else{ //若遇到非'0'字符
    19                 if(count == k){//表示出现连续 k 个 '0', 将字符 '0' 设置为空字符
    20                     while(count-- > 0){
    21                         chs[start++] = 0; //设置为空字符, ascii 码中 0 表示空字符(Null)
    22                     }
    23                 }
    24                 //重新统计
    25                 count = 0;
    26                 start = -1;
    27             }
    28         }
    29         //判断结尾是否出现 k 个 0' 字符
    30         if(count == k){
    31             while(count-- > 0){
    32                 chs[start++] = 0;
    33             }
    34         }
    35         
    36         return String.valueOf(chs);
    37     }
    38     
    39 }
  • 相关阅读:
    Guava Enums
    Guava CharMatcher
    Guava CaseFormat
    HotSpot Generations
    Java Run-Time Data Areas
    Reloading Java Classes 201: How do ClassLoader leaks happen? Translation
    Guava BiMap AbstractBiMap
    Reloading Java Classes 101: Objects, Classes and ClassLoaders Translation
    Guava CompoundOrdering
    Chapter 4 -- Throwables
  • 原文地址:https://www.cnblogs.com/zlxyt/p/10531880.html
Copyright © 2011-2022 走看看