Advertisement
Kali_prasad

findMaxSubString with adj chars diff less than k

Dec 19th, 2024
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | None | 0 0
  1.  
  2. import java.util.*;
  3. public class Main
  4. {
  5.     private static String findMaxSubString(String s,int k){
  6.         if(s.length()==0) return "";
  7.        
  8.         char prev = s.charAt(0);
  9.         int resLen = 1;
  10.         int currLen = 1;
  11.         int endingInd = 0;
  12.         for(int i =1;i<s.length();i++){
  13.             char curr = s.charAt(i);
  14.  
  15.             if(Math.abs(curr-prev)<=k){
  16.                 currLen+=1;
  17.             }else{
  18.                 currLen=1;
  19.             }
  20.            
  21.             if(currLen>resLen){
  22.                 resLen = currLen;
  23.                 endingInd=i;
  24.             }
  25.             prev = curr;
  26.         }
  27.         int startingInd = endingInd-resLen+1;
  28.         return s.substring(startingInd,endingInd+1);
  29.     }
  30.     public static void main(String[] args) {
  31.         Scanner sc = new Scanner(System.in);
  32.         String s = sc.nextLine();
  33.         int k = sc.nextInt();
  34.        
  35.         System.out.println(findMaxSubString(s,k));
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement