剑指offer 替换空格

剑指offer60天计划

Posted by liuwenzi on July 22, 2020
阅读数:

替换空格


请实现一个函数,把字符串 s 中的每个空格替换成”%20”。

示例 1:

1
2
输入s = "We are happy."
输出"We%20are%20happy."

题解

  • 用st

  • ringbuffer,将字符串从前往后扫描,遇到空格则将“%20”加上,否则直接加上扫描到的字符

    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      
      class Solution {
          public String replaceSpace(String s) {
              int length = s.length();
              StringBuffer sb = new StringBuffer();
              char[] cc = s.toCharArray();
              for (char c: cc){
                  if (c == 32){
                      sb.append("%20");
                  }else {
                      sb.append(c);
                  }
              }
              return sb.toString();
          }
      }
      

      9U23Ik