Advertisement
saurav_kalsoor

String Transformations - JAVA

Sep 28th, 2022
555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Author : Saurav Kalsoor
  2. // String Transformations - JAVA
  3.  
  4.  
  5. import java.util.*;
  6.  
  7. public class Test {
  8.  
  9.     static Scanner sc = new Scanner(System.in);
  10.     public static void main(String[] args) {
  11.         int n = sc.nextInt();
  12.         int k = sc.nextInt();
  13.  
  14.         String str = sc.next();
  15.    
  16.    
  17.         System.out.println(stringTransformations(n, k, str));
  18.     }
  19.    
  20.     public static int stringTransformations(int n, int k, String s){
  21.         char[] str = s.toCharArray();
  22.         int first = -1, last = -1;
  23.         for(int i = 0;i < n; i++){
  24.             if(str[i] == '1'){
  25.                 if(first == -1){
  26.                     first = i;
  27.                 }else{
  28.                     last = i;
  29.                 }
  30.             }
  31.         }
  32.  
  33.         if(first == -1){
  34.             return 0;
  35.         }else if(last == -1){
  36.             return 1;
  37.         }
  38.  
  39.         int count = 2;
  40.         str[first] = '2';
  41.         str[last] = '2';
  42.  
  43.         int prevChanged = first;
  44.  
  45.         while(prevChanged < last){
  46.  
  47.             if(last - prevChanged <= k)
  48.                 return count;
  49.            
  50.             int i = -1;
  51.             for(int j = prevChanged+1; j <= Math.min(n - 1, (prevChanged + k)); j++){
  52.                 if(str[j] == '1'){
  53.                     i = j;
  54.                 }
  55.             }
  56.  
  57.             if(i == -1){
  58.                 return -1;
  59.             }
  60.  
  61.             prevChanged = i;
  62.             str[prevChanged] = '2';
  63.             count++;
  64.            
  65.         }
  66.  
  67.         return count;
  68.     }
  69.  
  70. }
  71.  
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement