【问题描述】[简单]
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。示例 1:输入:s = "We are happy."
输出:"We%20are%20happy."限制:0 <= s 的长度 <= 10000
【解答思路】
1. 复制大法
时间复杂度:O(N) 空间复杂度:O(N)
class Solution {public String replaceSpace(String s) {int length = s.length();char[] array = new char[length * 3];int size = 0;for (int i = 0; i < length; i++) {char c = s.charAt(i);if (c == ' ') {array[size++] = '%';array[size++] = '2';array[size++] = '0';} else {array[size++] = c;}}String newStr = new String(array, 0, size);return newStr;}
}
2. StringBuilder/Buffer
时间复杂度:O(N) 空间复杂度:O(N)
class Solution {public String replaceSpace(String s) {StringBuilder res = new StringBuilder();for(Character c : s.toCharArray()){if(c == ' ') res.append("%20");else res.append(c);}return res.toString();}
}
【总结】
1.Java StringBuffer 和 StringBuilder 类
2.处理字符串 逐个比较
2.1转换字符数组(推荐)char[]ch=s.toCharArray();
2.2 使用charAt() char c = s.charAt()
转载链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/solution/mian-shi-ti-05-ti-huan-kong-ge-ji-jian-qing-xi-tu-/
来源:力扣(LeetCode)
参考链接:https://www.runoob.com/java/java-stringbuffer.html