r/dailyprogrammer • 1 2 • Jun 10 '13

[Easy] Longest Two-Character Sub-String

(Easy): Longest Two-Character Sub-String

This programming challenge is a classic interview question for software engineers: given a string, find the longest sub-string that contains, at most, two characters.

Author: /u/Regul

Formal Inputs & Outputs

Input Description

Through standard console input, you will be given a string to search, which only contains lower-case alphabet letters.

Output Description

Simply print the longest sub-string of the given string that contains, at most, two unique characters. If you find multiple sub-strings that match the description, print the last sub-string (furthest to the right).

Sample Inputs & Outputs

Sample Inputs

abbccc
abcabcabcabccc
qwertyytrewq

Sample Outputs

bbccc
bccc
tyyt
62 Upvotes

129 comments sorted by

View all comments

Show parent comment

3

u/eBtDMoN2oXemz1iKB Jun 10 '13

Hi, I liked your approach to the problem and used it in my own solution. Ruby, 9 lines.

best, sub, str = '', '', ARGV.shift
str.chars.each_index do |i|
  str[i..-1].each_char do |c|
    sub << c
    best = sub.dup if sub.chars.uniq.size <= 2 && sub.size >= best.size
  end
  sub = ''
end
puts best

2

u/TweenageDream Jun 11 '13

Nice job! Looks very clean! I'm gonna have to look up the difference between clone and dup, dup looks like its more shallow mem copy

1

u/eBtDMoN2oXemz1iKB Jun 11 '13

Thank you! I am not clear on all of the differences between dup and clone but according to stackoverflow

By default, there are two differences: Firstly, the singleton class is not copied by dup, but it is by clone. Secondly, dup does not preserve the frozen state, but clone does.

http://stackoverflow.com/questions/10183370/whats-the-differences-between-ruby-dup-and-clone-method