Skip to content

Instantly share code, notes, and snippets.

@vaibhavpandeyvpz
Created June 23, 2024 08:32
Show Gist options
  • Save vaibhavpandeyvpz/e22c24b3bf09746339dd637802f4ba4f to your computer and use it in GitHub Desktop.
Save vaibhavpandeyvpz/e22c24b3bf09746339dd637802f4ba4f to your computer and use it in GitHub Desktop.
One of my friend asked for a clean solution to an interview question he was asked i.e., "reverse alphabetical sequences in a string" in Java. Clean would ofcourse be using StringBuilder but I'm not if using too many built-ins (we using RegExp already) is allowed during tech interviews.
package com.vaibhavpandey;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class StrRev {
static Pattern AZ = Pattern.compile("[a-zA-Z]+");
static String reverse(String string) {
char[] characters = string.toCharArray();
char[] reversed = new char[characters.length];
for (int i = characters.length - 1, j = 0; i >= 0; i--, j++) {
reversed[j] = characters[i];
}
return new String(reversed);
}
public static void main(String[] args) {
String input = "1234abcd5678efgh";
String output = "<mismatch>"; // expected 1234dcba5678hgfe
Matcher matcher = AZ.matcher(input);
if (matcher.find()) {
output = matcher.replaceAll(s -> reverse(s.group()));
// or simply: output = matcher.replaceAll(s -> new StringBuilder(s.group()).reverse().toString());
}
System.out.println(output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment