Skip to content

Instantly share code, notes, and snippets.

@IngeFrodo
Last active April 15, 2020 17:50
Show Gist options
  • Save IngeFrodo/abaaf7bb8de4cda3d5fc5cacc2d9117a to your computer and use it in GitHub Desktop.
Save IngeFrodo/abaaf7bb8de4cda3d5fc5cacc2d9117a to your computer and use it in GitHub Desktop.
class PerformStringShifts {
public String stringShift(String s, int[][] shift) {
int shiftNumber = 0;
for (int[] shiftOperation : shift) {
if (shiftOperation[0] == 1) {
shiftNumber += shiftOperation[1];
} else {
shiftNumber -= shiftOperation[1];
}
}
char[] charArray = s.toCharArray();
shiftNumber %= charArray.length;
if (shiftNumber < 0) {
shiftNumber += charArray.length;
}
shiftArray(charArray, shiftNumber);
return new String(charArray);
}
private void shiftArray(char[] charArray, int shiftNumber) {
reverse(charArray, 0, charArray.length - 1);
reverse(charArray, 0, shiftNumber - 1);
reverse(charArray, shiftNumber, charArray.length - 1);
}
private void reverse(char[] charArray, int left, int right) {
while (left < right) {
swap(charArray, left++, right--);
}
}
private void swap(char[] charArray, int from, int to) {
char c = charArray[from];
charArray[from] = charArray[to];
charArray[to] = c;
}
}
@munguial
Copy link

Nicely done. I like how you created small methods, your code looks very clean.

One minor comment: would the if condition in line 14 ever be true? As far as I know the module operator will always return a positive value

@IngeFrodo
Copy link
Author

Yes, it can be negative the % returns the same sign as the dividend

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment