Skip to content

Instantly share code, notes, and snippets.

@courtneyfaulkner
Created September 6, 2017 04:24
Show Gist options
  • Save courtneyfaulkner/c6e892f6f51d517e834a56063de9ad45 to your computer and use it in GitHub Desktop.
Save courtneyfaulkner/c6e892f6f51d517e834a56063de9ad45 to your computer and use it in GitHub Desktop.
[ReverseArray] #practice
class ReverseArray {
/*
Input: str = "a,b$c"
Output: str = "c,b$a"
Note that $ and , are not moved anywhere.
Only subsequence "abc" is reversed
Input: str = "Ab,c,de!$"
Output: str = "ed,c,bA!$"
*/
static void main(String[] args) {
println reverse('a,b$c')
println reverse('Ab,c,de!$')
}
static String reverse(String input) {
char[] arr = input.toCharArray()
int i = 0, j = arr.length
if (j % 2 == 0) {
j = j / 2
} else {
j = (j - 1) / 2
}
int k = arr.length - 1
while (k > j) {
if (!swappable(arr[i])) {
i++
}
if (!swappable(arr[k])) {
k--
}
if (swappable(arr[i]) && swappable(arr[k])) {
Character temp = arr[k]
arr[k] = arr[i]
arr[i] = temp
i++
k--
}
}
arr.toString()
}
static boolean swappable(Character c) {
return c.toString() ==~ /[A-Za-z0-9]/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment