Backspaces in String Challenge Using Java


The challenge

Assume "#" is like a backspace in string. This means that string "a#bc#d" actually is "bd"

Your task is to process a string with "#" symbols.

Examples

"abc#d##c"      ==>  "ac"
"abc##d######"  ==>  ""
"#######"       ==>  ""
""              ==>  ""

Test cases

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void testCleanString() {
        final BackspacesInString bis = new BackspacesInString();
        assertEquals("ac", bis.cleanString("abc#d##c"));
        assertEquals("", bis.cleanString("abc####d##c#"));
    }
}

The solution in Java

Option 1:

public class BackspacesInString {
  public String cleanString(String s) {
    StringBuilder current = new StringBuilder("");
    int idx = 0;
    
    for (int i=0; i<s.length(); i++) {
      String c = Character.toString(s.charAt(i));
      if (c.equals("#")) {
        // backspace
        if (idx>0) {
          idx--;
          current.deleteCharAt(idx);
        }
      } else {
        // string
        System.out.println(c);
        current.append(c);
        idx++;
      }
    }
    
    return current.toString();
  }
}

Option 2 (using regex):

class BackspacesInString {
  static String cleanString(String s) {
    while (s.matches(".*#.*")) s = s.replaceFirst(".?#", "");
    return s;
  }
}

Option 3 (using substring):

public class BackspacesInString {
  public String cleanString(String s) {
    int idx = s.indexOf("#");
    return idx < 0 ? s : idx == 0 ? cleanString(s.substring(1)) : cleanString(s.substring(0, idx-1) + s.substring(idx+1)); 
  }
}