Gyh's Braindump

CN-05.Replace Blank

tags
two pointers, trick
source
leetcode-cn

Edge Cases

Solution 1

use StringBuilder, iterate from start to end

Complexity

  • time: O(N)
  • space: O(N)

Solution 2

  1. compute new length
  2. apply new char array
  3. scan from back to start
class Solution {
    public String replaceSpace(String s) {
        int spaceCount = 0;
        for (char c: s.toCharArray()) {
            if (c == ' ') spaceCount++;
        }

        int newLen = spaceCount * 2 + s.length();
        char[] newStr = new char[newLen];
        int p1 = newLen - 1, p2 = s.length() - 1;
        while (p2 >= 0) {
            if (s.charAt(p2) != ' ') {
                newStr[p1--] = s.charAt(p2--);
            } else {
                newStr[p1--] = '0';
                newStr[p1--] = '2';
                newStr[p1--] = '%';
                p2--;
            }
        }

        return new String(newStr);
    }
}

Complexity

  • time: O(N)
  • space: O(N)