Advertisement
saurav_kalsoor

Smallest Substring - JAVA

Nov 19th, 2021
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Test {
  4.  
  5.     static Scanner sc = new Scanner(System.in);
  6.  
  7.     public static void main(String[] args) {
  8.  
  9.         int n = sc.nextInt();
  10.         String s = sc.next();
  11.         int res = smallestSubstring(n, s);
  12.         System.out.println(res);
  13.     }
  14.  
  15.     public static int smallestSubstring(int n, String s) {
  16.         char[] temp = s.toCharArray();
  17.  
  18.         // Check for length of 2
  19.         for (int i = 0; i < n - 1; i++) {
  20.             if (temp[i] == 'x' && temp[i + 1] == 'x')
  21.                 return 2;
  22.         }
  23.  
  24.         // Check for length of 3
  25.         for (int i = 0; i < n - 2; i++) {
  26.             if (temp[i] == 'x' && temp[i + 2] == 'x')
  27.                 return 3;
  28.         }
  29.  
  30.         // Check for length of 4
  31.         for (int i = 0; i < n - 3; i++) {
  32.             if (temp[i] == 'x' && temp[i + 3] == 'x' && temp[i + 1] != temp[i + 2])
  33.                 return 4;
  34.         }
  35.  
  36.         // Check for length of 7
  37.         for (int i = 0; i < n - 6; i++) {
  38.             if (temp[i] == 'x' && temp[i + 3] == 'x' && temp[i + 6] == 'x') {
  39.                 int countY = 0, countZ = 0;
  40.                 for (int j = i + 1; j <= i + 5; j++) {
  41.                     if (temp[j] == 'y')
  42.                         countY++;
  43.                     else if (temp[j] == 'z')
  44.                         countZ++;
  45.                 }
  46.  
  47.                 if (countY == 2 && countZ == 2)
  48.                     return 7;
  49.             }
  50.         }
  51.         return -1;
  52.     }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement