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

5

u/YZBot Jun 11 '13

Java

import java.util.HashSet;
import java.util.Set;

public class DailyProgrammer129 {

	public static void main(String[] args) {
		String s = args[0];	
		String longest = "";
		
		for (int i = 0; i < s.length(); i++) {
			Set<Character> tempSet = new HashSet<Character>();
			
			for (int j = i; j < s.length(); j++) {
				tempSet.add(s.charAt(j));		
				
				if (tempSet.size() <= 2 && s.substring(i,j+1).length() > longest.length()) {		
					longest = s.substring(i,j+1);
				}
			}						
		}
		System.out.println(longest);
	}
}

First time posting code. Feels like cheating using a Set.

2

u/[deleted] Jun 21 '13

Ahh, but this solution requires that every possible 2+ length substring be checked.