Skip to content
Advertisement

Efficient solution to codingBat riddle starOut in Java

The problem I am talking about is this

Problem statment:

Return a version of the given string, where for every star () in the string the star and the chars immediately to its left and right are gone. So “abcd” yields “ad” and “ab**cd” also yields “ad”.

starOut(“ab*cd”) → “ad”

starOut(“ab**cd”) → “ad”

starOut(“sm*eilly”) → “silly”

The solution I got was a little messy I have used about 6 if statements and a handling for one particular case, looking for cleaner solutions with lesser ifs.

Please do not use more than 1 loop and collections or regex.

Below is my solution:

public String starOut(String str) {
  String result="";
  boolean currentFlag=false;
  
  if(str.length()==0)
  return result;
  
  for(int i=0;i+1<str.length();i++)
  {
    if(str.charAt(i)=='*')
    {
       i+=1;
       currentFlag=true;
       continue;
     }
     if(str.charAt(i+1)=='*')
     {
        i+=2;
        continue;
     }
     if((i>0)&&str.charAt(i-1)=='*')
     {
        continue;
     }
     result+=str.substring(i,i+1);
     currentFlag=false;

   }
   
  if(!(currentFlag)&&(str.length()==3)&&(str.charAt(1)=='*'))
      return ""; 
      
   if((str.charAt(str.length()-1)!='*')&!(currentFlag))
     return result+=str.charAt(str.length()-1);
    else
      return result;
}

Advertisement

Answer

Pseudocode:

Step through all the characters in the string. If you land on an asterisk, don’t record it. Peek left, and if you see an asterisk, don’t record it. Peek right if you see an asterisk, don’t record it. If none of the above things happen, record it.

Java code:

public static String starOut(String s) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '*') continue;
        if (i > 0 && s.charAt(i - 1) == '*') continue;
        if (i < s.length() - 1 && s.charAt(i + 1) == '*') continue;
            
        sb.append(s.charAt(i));
    }

    return sb.toString();
}

Note: I see a lot of answers pop up that are concatenating String objects in the loop instead of using a StringBuilder. Don’t do that. It’s very inefficient.

Advertisement