Backspaces in String Challenge using Java

0 min read 188 words

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)); 
  }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags