blob: e290f176d7b3e520ccba082da8961078e973ecb6 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# Task 1: Duplicate Removals
# Submitted by: Mohammad Sajid Anwar
#
# You are given a string, $str, consisting of lowercase English letters.
#
# Write a script to return the final string after all duplicate removals have been made. Repeat duplicate removals on the given string until we no longer can.
#
# A duplicate removal consists of choosing two adjacent and equal letters and removing them.
#
# Example 1
# Input: $str = 'abbaca'
# Output: 'ca'
#
# Step 1: Remove 'bb' => 'aaca'
# Step 2: Remove 'aa' => 'ca'
#
# Example 2
# Input: $str = 'azxxzy'
# Output: 'ay'
#
# Step 1: Remove 'xx' => 'azzy'
# Step 2: Remove 'zz' => 'ay'
#
# Example 3
# Input: $str = 'aaaaaaaa'
# Output: ''
#
# Step 1: Remove 'aa' => 'aaaaaa'
# Step 2: Remove 'aa' => 'aaaa'
# Step 3: Remove 'aa' => 'aa'
# Step 4: Remove 'aa' => ''
#
# Example 4
# Input: $str = 'aabccba'
# Output: 'a'
#
# Step 1: Remove 'aa' => 'bccba'
# Step 2: Remove 'cc' => 'bba'
# Step 3: Remove 'bb' => 'a'
#
# Example 5
# Input: $str = 'abcddcba'
# Output: ''
#
# Step 1: Remove 'dd' => 'abccba'
# Step 2: Remove 'cc' => 'abba'
# Step 3: Remove 'bb' => 'aa'
# Step 4: Remove 'aa' => ''
def get_noduplicate(str)
str_orig = str.dup
while str =~ /(\w)\1/
str.gsub!(/(\w)\1/, '')
end
printf "'%s' -> '%s'\n", str_orig, str;
end
str = 'abbaca'
get_noduplicate(str)
str = 'azxxzy'
get_noduplicate(str)
str = 'aaaaaaaa'
get_noduplicate(str)
str = 'aabccba'
get_noduplicate(str)
str = 'abcddcba'
get_noduplicate(str)
|