Java parentheses flip string

How do I replace a string so that "(" becomes ")" and ")" becomes "("?

Solution

use. Replace (), but if you replace) (then (and) you will eventually get all) is tempting Instead, iterate over the string and use string builder to build the string

String swapParens(String s) {
    StringBuilder sb = new StringBuilder();
    sb.ensureCapacity(s.length()); // preallocate to prevent resizing
    for(int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        switch(c) {
            case ')': sb.append('('); break;
            case '(': sb.append(')'); break;
            default: sb.append(c);
        }
    }
    return sb.toString();

}

I know you can exchange something there as a placeholder, but if it already exists in your string, you'll have a big problem

Consider using "XXX" as the swap string If your string is "abcx (YZ)", you replace it (with XXX, you finally get "abcxxxxyz)" and then you replace it) (so you have "abcxxxxyz (". Then you replace XXX), so you have "ABC) XYZ (". Of course, it's not cool!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>