Advertisement
elsemTim

v.2.0

Aug 9th, 2020 (edited)
1,761
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.58 KB | None | 0 0
  1. fun stringChallenge(str: String): String {
  2.     val result = recurseChallenge(str)
  3.     return result.length.toString()
  4. }
  5.  
  6. fun recurseChallenge(string: String): String {
  7.     val firstChar = string.first()
  8.     val isAllTheSame = string.all { it == firstChar }
  9.     if (isAllTheSame) {
  10.         return string
  11.     } else {
  12.         var position = 0
  13.         for (index in 0 until string.length - 1) {
  14.             val curValue = string[index]
  15.             val nextValue = string[index + 1]
  16.             if (curValue != nextValue) {
  17.                 position = index
  18.                 break
  19.             }
  20.         }
  21.         val oldSequence = string[position] + string[position + 1].toString()
  22.         val newString =
  23.             string.replaceFirst(
  24.                 oldSequence,
  25.                 checkNeedReplaceOrNot(string[position], string[position + 1]),
  26.                 true
  27.             )
  28.         println(newString)
  29.         return recurseChallenge(newString)
  30.     }
  31. }
  32.  
  33. fun checkNeedReplaceOrNot(firstChar: Char, secondChar: Char): String = if (firstChar == secondChar) {
  34.     firstChar.toString() + secondChar.toString()
  35. } else {
  36.     thirdChar(firstChar, secondChar)
  37. }
  38.  
  39. fun thirdChar(firstChar: Char, secondChar: Char): String {
  40.     val twoChar: String = firstChar.toString() + secondChar.toString()
  41.     if (!twoChar.contains("a")) {
  42.         return "a"
  43.     }
  44.     if (!twoChar.contains("b")) {
  45.         return "b"
  46.     }
  47.     if (!twoChar.contains("c")) {
  48.         return "c"
  49.     }
  50.     return twoChar
  51. }
  52.  
  53.  
  54. fun main(args: Array<String>) {
  55.     println(stringChallenge(readLine()!!))
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement