去掉字符中連續出現的k個子串

題目:

思路:這個題也是遍歷一遍數組,當遇到特殊字符0時進行處理。需要注意的是以下幾點:

(1)我自己寫輸入輸出的時候要注意,都是用next()。然後再進行轉換

(2)在取出字符0的時候,直接給相應位置的設置爲數字0就可以了。在輸出的時候判斷以下不是0再輸出就可以了

代碼:

import java.io.*;
import java.util.*;
public class zcy1 {
    public  static void main(String[]args){
       Scanner sc=new Scanner(System.in);

            String k1=sc.nextLine();
            String a=sc.nextLine();

       int k=Integer.valueOf(k1);

        if(a==null||k<1){
            System.out.println(-1);
        }
        else{
            char[]a1=a.toCharArray();
            int count=0;
            int start=-1;
            for(int i=0;i<a1.length;i++){
                if(a1[i]=='0'){
                    count++;
                    start=start==-1?i:start;
                }
                else{
                    if(count==k){
                        while(count--!=0){
                            a1[start++]=0;
                        }
                        count=0;
                        start=-1;
                    }
                }
            }
            if(count==k){
                while(count--!=0)
                a1[start++]=0;
            }
            for(int i=0;i<a1.length;i++){
                if(a1[i]!=0)
                System.out.print(a1[i]);
            }

        }
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章