Problem of the Day:
Remove Duplicate Characters and Digits with Different Rules
You are given a string s consisting of lowercase English letters and digits (0–9).
You must transform the string in two steps:
- Characters (a–z):
- Traverse from left to right.
- Keep only the first occurrence of each character.
- Remove all later duplicates.
Digits (0–9):
- Traverse from right to left.
- Keep only the first digit you encounter (the rightmost occurrence in the original string).
- Remove earlier duplicates.
Return the final transformed string.
1.Input: programming123321
After Step1: progamin123321
Final: progamin321
(keeps the rightmost 1,2,3 — final digits appear as the left-to-right order of their last occurrences)
2. Input: abc11223344
After Step1: abc11223344
Final: abc1234
3. Input: a1b2c1d2e3
After Step1: a1b2c1d2e3
Final: abc1d2e3
After Step1: progamin123321
Final: progamin321
(keeps the rightmost 1,2,3 — final digits appear as the left-to-right order of their last occurrences)
After Step1: abc11223344
Final: abc1234
After Step1: a1b2c1d2e3
Final: abc1d2e3
class LeftRight {
ReplyDeletepublic static void main(String args[]) {
String str = "31aa22bb3b1";
System.out.println("Original String :" + str);
for (int i = 0; i < str.length(); i++) {
boolean flag = true;
if (str.charAt(i) >= 48 && str.charAt(i) <= 58) {
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
System.out.print(str.charAt(i));
}
} else {
for (int j = 0; j < i; j++) {
if (str.charAt(i) == str.charAt(j)) {
flag = false;
}
}
if (flag) {
System.out.print(str.charAt(i));
}
}
}
}
}