Optimize solution using Stack In java


#1

public class Solution {
public String solve(String A) {

    Stack<Character> st=new Stack();
    
Map<Character,Integer> map=new HashMap<Character,Integer>();
 for (char ch : A.toCharArray())

{
if(!map.containsKey(ch))
map.put(ch,1);
else
map.put(ch,map.get(ch)+1);
}

boolean used[]=new boolean[26];
StringBuffer sb=new StringBuffer();
for (char ch:A.toCharArray())
{
map.put(ch,map.get(ch)-1);
if(used[ch-‘a’]==true ) continue;

while(!st.isEmpty() && st.peek()>ch && map.get(st.peek())>0)
{
    used[st.peek()-'a']=false;
    st.pop();
}
st.push(ch);
used[ch- 'a']=true;

}
for(char ch:st)
{
sb.append(ch);
}

    return sb.toString();
}

}