r/dailyprogrammer – [Easy] Longest Two-Character Sub-String

This is my solution to a programming challenge found at reddit.com/r/dailyprogrammer. This problem can be found at longest two character substring. My solution was to step through each position of the string and place whatever character that position holds into a temporary Set. A Set will only contain unique items so if I end up with more than two I know my substring holds more than two unique characters.


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++) {

                if (tempSet.size() <= 2 && s.substring(i,j+1).length() > longest.length()) {        
                    longest = s.substring(i,j+1);

This entry was posted in Java, r/dailyprogrammer. Bookmark the permalink.

Leave a Reply