Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stringbuilder.replace

Consider the following inputs:

String[] input = {"a9", "aa9", "a9a9", "99a99a"};

What would be the most efficient way whilst using a StringBuilder to replace any digit directly prior to a nine with the next letter after it in the alphabet?

After processing these inputs the output should be:

String[] output = {"b9", "ab9", "b9b9", "99b99a"}

I've been scratching my head for a while and the StringBuilder.setCharAt was the best method I could think of.

Any advice or suggestions would be appreciated.

like image 622
Tony Avatar asked Oct 24 '22 10:10

Tony


1 Answers

Since you have to look at every character, you'll never perform better than linear in the size of the buffer. So you can just do something like

for (int i=1; buffer.length() ++i) // Note this starts at "1"
    if (buffer.charAt[i] == '9')
        buffer.setCharAt(i-1, buffer.getCharAt(i-1) + 1);
like image 104
Ernest Friedman-Hill Avatar answered Nov 02 '22 05:11

Ernest Friedman-Hill