Saturday, December 31, 2011

Escape all % characters in a string; % is the escape character

Example :
Input : India has GDP of 10% in 2009
Output : Input has GDP of 10%% in 2009

It is usually not be possible to do this in-place since the original unescaped string may not have enough space in the array to store the additional escape characters. But if we create a new array, O(n) algo is possible, though space complexity will increase.

String escapePercent(String input) {
    StringBuilder sb = new StringBuilder();
    char[] str = input.toCharArray();
 
    for (int i = 0; i < input.length(); i++) {
        if (str[i] == ‘%’) sb.append(‘%’);
        sb.append(str[i]);
    }
 
    return new String(sb);
}

0 comments:

Post a Comment