Skip to content

Instantly share code, notes, and snippets.

@munguial
Last active April 15, 2020 01:54
Show Gist options
  • Save munguial/8a6254af2b7b9cc3356c262c889800b8 to your computer and use it in GitHub Desktop.
Save munguial/8a6254af2b7b9cc3356c262c889800b8 to your computer and use it in GitHub Desktop.
Day 14 - Perform String Shifts
// https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/529/week-2/3299/
class Solution {
fun stringShift(s: String, shift: Array<IntArray>): String {
val singleShift: Pair<Int, Int> = calculateSingleShift(shift)
return shiftCharacters(s, singleShift.first, singleShift.second % s.length)
}
fun shiftCharacters(s: String, direction: Int, n: Int): String {
if (n == 0) {
return s
}
val a: String
val b: String
if (direction == 1) {
a = s.substring(0, s.length - n)
b = s.substring(s.length - n, s.length)
} else {
a = s.substring(0, n)
b = s.substring(n, s.length)
}
return b + a
}
fun calculateSingleShift(shifts: Array<IntArray>): Pair<Int, Int> {
var shiftCounter = 0
for (shift in shifts) {
val multiplier = if (shift[0] == 0) -1 else 1
shiftCounter += shift[1] * multiplier
}
when {
shiftCounter < 0 -> return Pair(0, -shiftCounter)
else -> return Pair(1, shiftCounter)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment