We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static String superReducedString(String s) {
char[] arr = s.toCharArray();
//Since String is immutable we can't directly alter the string so
//use StringBuilder to store the altered String
java.lang.StringBuilder sb = new java.lang.StringBuilder();
for(char c : arr){
if(sb.length()>0 &&(sb.charAt(sb.length()-1)==c)){
sb.deleteCharAt(sb.length()-1);
}else{
sb.append(c);
}
}
if(sb.length()==0){
return "Empty String";
}
return sb.toString();
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Super Reduced String
You are viewing a single comment's thread. Return to all comments →
public static String superReducedString(String s) { char[] arr = s.toCharArray(); //Since String is immutable we can't directly alter the string so //use StringBuilder to store the altered String java.lang.StringBuilder sb = new java.lang.StringBuilder(); for(char c : arr){ if(sb.length()>0 &&(sb.charAt(sb.length()-1)==c)){ sb.deleteCharAt(sb.length()-1); }else{ sb.append(c); } } if(sb.length()==0){ return "Empty String"; } return sb.toString(); }