Microsoft Online Assessment (OA) - String Without 3 Identical Consecutive Letters
Given a string S
having lowercase English letters, returns a string with no instances of three identical consecutive letters,
obtained from S
by deleting the minimum possible number of letters.
Example 1:
Input: eedaaad
Output: eedaad
Explanation:
One occurrence of the letter a
is deleted.
Example 2:
Input: xxxtxxx
Output: xxtxx
Explanation:
Note that the letter x
can occur more than three times in the returned string if the occurrences are not consecutive.
Example 3:
Input: uuuuxaaaaxum
Output: uuxaaxum
Try it yourself
Implementation
1def filter_string(s: str) -> str:
2 news = s[0:2]
3 for i in range(2, len(s)):
4 # Do not append if the previous chars are the same
5 if s[i] != s[i - 1] or s[i] != s[i - 2]:
6 news += s[i]
7 return news
8
9if __name__ == "__main__":
10 s = input()
11 res = filter_string(s)
12 print(res)
13
1import java.util.Scanner;
2
3class Solution {
4 public static String filterString(String s) {
5 StringBuilder sb = new StringBuilder();
6 sb.append(s.charAt(0));
7 sb.append(s.charAt(1));
8 for (int i = 2; i < s.length(); ++i) {
9 if (s.charAt(i) != s.charAt(i - 1) || s.charAt(i) != s.charAt(i - 2)) {
10 sb.append(s.charAt(i));
11 }
12 }
13 return sb.toString();
14 }
15
16 public static void main(String[] args) {
17 Scanner scanner = new Scanner(System.in);
18 String s = scanner.nextLine();
19 scanner.close();
20 String res = filterString(s);
21 System.out.println(res);
22 }
23}
24
1"use strict";
2
3function filterString(s) {
4 const res = [s.charAt(0), s.charAt(1)];
5 for (let i = 2; i < s.length; ++i) {
6 if (s.charAt(i) !== s.charAt(i - 1) || s.charAt(i) !== s.charAt(i - 2)) {
7 res.push(s[i]);
8 }
9 }
10 return res.join("");
11}
12
13function* main() {
14 const s = yield;
15 const res = filterString(s);
16 console.log(res);
17}
18
19class EOFError extends Error {}
20{
21 const gen = main();
22 const next = (line) => gen.next(line).done && process.exit();
23 let buf = "";
24 next();
25 process.stdin.setEncoding("utf8");
26 process.stdin.on("data", (data) => {
27 const lines = (buf + data).split("\n");
28 buf = lines.pop();
29 lines.forEach(next);
30 });
31 process.stdin.on("end", () => {
32 buf && next(buf);
33 gen.throw(new EOFError());
34 });
35}
36
Got a question? Ask the Monster Assistant anything you don't understand.
Still not clear?  Submit the part you don't understand to our editors. Or join our Discord and ask the community.