LeetCode面试题 01.03 URL化
题目
解答
package leetcode.editor.cn;//leetcode submit region begin(Prohibit modification and deletion)
class Solution {public String replaceSpaces(String S, int length) {if (S == null || S.isEmpty() || length <= 0) {return "";}StringBuilder sb = new StringBuilder(length);for (int i = 0; i < length; ++i) {if (S.charAt(i) == ' ') {sb.append("%20");} else {sb.append(S.charAt(i));}}return sb.toString();}
}
//leetcode submit region end(Prohibit modification and deletion)
测试用例
package leetcode.editor.cn;import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;public class SolutionTest {private Solution s = null;@Beforepublic void setUp() throws Exception {s = new Solution();}@Testpublic void test1() {String result = s.replaceSpaces("Mr John Smith ", 13);Assert.assertEquals("Mr%20John%20Smith", result);}@Testpublic void test2() {String result = s.replaceSpaces(" ", 5);Assert.assertEquals("%20%20%20%20%20", result);}
}