saurav_kalsoor

Smallest Substring - KOTLIN

Nov 23rd, 2021 (edited)
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.23 KB | None | 0 0
  1. import java.util.*
  2.  
  3. var sc: Scanner = Scanner(System.`in`)
  4.  
  5. fun main() {
  6.     val n: Int = sc.nextInt()
  7.     val s: String = sc.next()
  8.     val res = smallestSubstring(n, s)
  9.     println(res)
  10. }
  11.  
  12. fun smallestSubstring(n: Int, s: String): Int {
  13.     val temp: CharArray = s.toCharArray()
  14.  
  15.     // Check for length of 2
  16.     for (i in 0 until n - 1) {
  17.         if (temp[i] == 'x' && temp[i + 1] == 'x')
  18.             return 2
  19.     }
  20.  
  21.     // Check for length of 3
  22.     for (i in 0 until n - 2) {
  23.         if (temp[i] == 'x' && temp[i + 2] == 'x')
  24.             return 3
  25.     }
  26.  
  27.     // Check for length of 4
  28.     for (i in 0 until n - 3) {
  29.         if (temp[i] == 'x' && temp[i + 3] == 'x' && temp[i + 1] != temp[i + 2])
  30.             return 4
  31.     }
  32.  
  33.     // Check for length of 7
  34.     for (i in 0 until n - 6) {
  35.         if (temp[i] == 'x' && temp[i + 3] == 'x' && temp[i + 6] == 'x') {
  36.             var countY = 0
  37.             var countZ = 0
  38.             for (j in i + 1..i + 5) {
  39.                 if (temp[j] == 'y')
  40.                     countY++
  41.                 else if (temp[j] == 'z')
  42.                     countZ++
  43.             }
  44.             if (countY == 2 && countZ == 2)
  45.                 return 7
  46.         }
  47.     }
  48.     return -1
  49. }
  50.  
Add Comment
Please, Sign In to add comment