Leetcode 1417. Reformat The String
You are given an alphanumeric string s
. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to reformat the string such that no two adjacent characters are of the same type. More formally, no two adjacent characters should both be letters or both be digits.
Return the reformatted string or return an empty string if it is impossible to reformat the string.
""
.public class ReformatString {
public String reformat(String s) {
StringBuilder letters = new StringBuilder();
StringBuilder digits = new StringBuilder();
// Separate letters and digits
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
letters.append(c);
} else {
digits.append(c);
}
}
// Check if reformatting is possible
if (Math.abs(letters.length() - digits.length()) > 1) {
return "";
}
// Result builder
StringBuilder result = new StringBuilder();
int i = 0, j = 0;
// Decide starting character type
boolean shouldPickLetter = letters.length() >= digits.length();
// Merge letters and digits
while (i < letters.length() && j < digits.length()) {
if (shouldPickLetter) {
result.append(letters.charAt(i++));
} else {
result.append(digits.charAt(j++));
}
shouldPickLetter = !shouldPickLetter; // Alternate
}
// Add the remaining characters
if (i < letters.length()) {
result.append(letters.charAt(i));
} else if (j < digits.length()) {
result.append(digits.charAt(j));
}
return result.toString();
}
public static void main(String[] args) {
ReformatString rs = new ReformatString();
// Sample test cases
System.out.println(rs.reformat("a0b1c2")); // Expected "a0b1c2" or permutations
System.out.println(rs.reformat("leetcode")); // Expected ""
System.out.println(rs.reformat("1229857369")); // Expected ""
System.out.println(rs.reformat("covid2019")); // Expected "c2o0v1i9d" or permutations
System.out.println(rs.reformat("ab123")); // Expected "a1b2" or permutations
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?