Balanced String | Core Java Forum
M
Mustapha Rhouate Posted on 03/08/2020


M
Mustapha Rhouate Replied on 03/08/2020

Hi
Can you help solve this problem

Thanks


Y
Yogesh Chawla Replied on 03/08/2020

This piece of code will perform the desired task for us. If you find it little difficult to understand then we can make a little simpler code also which will also do the same.

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

public class findShortestBalancedSubstring {
	public static void main(String[] args) {
        System.out.println(getShortestFragment("ABcabbCa"));
        System.out.println(getShortestFragment("azABaabza"));
        System.out.println(getShortestFragment("CATattac"));
        System.out.println(getShortestFragment("TacoCat"));
        System.out.println(getShortestFragment("Madam"));
        System.out.println(getShortestFragment("AcZCbaBz"));
        System.out.println(getShortestFragment("aZABcabbCa"));
    }

    static String getShortestFragment(String str){
        for(int k=1;k<=str.length();k++){
            for(int i=0;i<str.length()-k+1;i++){
                Set<Character> lowerSet = new HashSet<>();
                Set<Character> upperSet = new HashSet<>();
                String temp = str.substring(i,i+k);
                char[] tempCharArr = temp.toCharArray();
                for(char ch : tempCharArr){
                if(Character.isLowerCase(ch))
                    lowerSet.add(ch);
                else
                    upperSet.add(ch);
                }
                if(containsAllElements(lowerSet, upperSet) && containsAllElements(upperSet, lowerSet)){
                    return temp;
                }
            }            
        }
        return "-1";   
    }

    static boolean containsAllElements(Set<Character> first, Set<Character> second){
        Set<Character> lower1 = new HashSet<>();
        Set<Character> lower2 = new HashSet<>();
        first.forEach((e) -> {
            lower1.add(Character.toLowerCase(e));
        });
       second.forEach((e) -> {
            lower2.add(Character.toLowerCase(e));
        });
        return lower1.containsAll(lower2);
    }
}

Regards


M
Mustapha Rhouate Replied on 03/08/2020

Thanks for quick replay

I will try it


Y
Yogesh Chawla Replied on 10/10/2020

Sure, You are welcome.