Improved balanced bracket question


  • 0
    E

    This was one of the questions I was asked in the interview. I wasn't able to implement it correctly.

    If input = (()) , the result will be (())
    If input = (() , the result will be 1()
    If input = ()) , the result will be ()-1
    If input = (())( , the result will be (())1
    If input = (())) , the result will be (())-1
    If input = ()(( , the result will be ()11
    If input = ))() , the result will be -1-1()
    

    I came up with the below code :

    public String balancedString(String input)
    {
    	StringBuilder builder = new StringBuilder();
    	if(input == null || input.length() < 2)
    	{
    		return builder.toString();
    	}
    	Stack<Character> stack = new Stack<Character>();
    	Map<Character, Character> bracketMap = new HashMap<Character, Character>();
    	bracketMap.put('(', ')');
    	
    	for(int index = 0; index < input.length(); index++)
    	{
    		char value = input.charAt(index);
    		if(bracketMap.containsKey(value))
    		{
    			stack.push(value);
    			
    			builder.append(value);
    		}
    		else if(bracketMap.containsValue(value))
    		{
    			if(!stack.isEmpty() && bracketMap.get(stack.peek()) == value)
    			{
    				stack.pop();
    				builder.append(value);
    			}
    		}
    	}
    	return builder.toString();
    }
    

    I am trying to fill up the logic to adjust the 1 and -1 for ( and ). Definitely, I have to use charAt somewhere , but I am confused to store that information in stack without being analyzing the balanced. Any idea or improvement would be helpful !

    Thanks !


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.