链接 https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/ 难度: #简单 题目 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 示例 1: 输入:s = "We are happy." 输出:"We%
链接
https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
难度: #简单
题目
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."输出:"We%20are%20happy."
限制:0 <= s 的长度 <= 10000
代码框架
class Solution {public String replaceSpace(String s) {
}
}
题目解析
解答思路1:
使用Sring自带的replace方法,
替换空格为目标字符串。
解答思路2:
按照顺序读取String的char字符,
判断每个char是否为空格,
替换空格为目标字符串。
同时使用StringBuilder拼接返回值。
读取String的char字符相关API:
public char charAt(int index)public char[] toCharArray()
测试用例
package edu.yuwen.sowrd.num05.solution;import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import edu.yuwen.sowrd.num05.sol2.Solution;
public class SolutionTest {
/**
* 输入:s = "We are happy."
* 输出:"We%20are%20happy."
*/
@Test
public void testCase1() {
Solution solution = new Solution();
String s = "We are happy.";
String res = solution.replaceSpace(s);
Assertions.assertEquals("We%20are%20happy.", res);
}
}
解答1 推荐
package edu.yuwen.sowrd.num05.sol1;public class Solution {
public String replaceSpace(String s) {
String res = s.replace(" ", "%20");
return res;
}
}
解答2
package edu.yuwen.sowrd.num05.sol2;public class Solution {
public String replaceSpace(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ' ') {
sb.append("%20");
} else {
sb.append(c);
}
}
return sb.toString();
}
}