(程序员面试金典)面试题 01.03. URL化

学而不思则罔思而不学则殆。此处仅记录我在力扣学习算法与数据结构的笔记,用于加深记忆

难度:简单

URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)

示例 1:

输入:"Mr John Smith    ", 13
输出:"Mr%20John%20Smith"


示例 2:

输入:"               ", 5
输出:"%20%20%20%20%20"
 

提示:

字符串长度在 [0, 500000] 范围内。

先看一下结果

执行用时:13 ms, 在所有 Java 提交中击败了54.81%的用户

内存消耗:45.9 MB, 在所有 Java 提交中击败了82.05%的用户

思路:

1. 就是先找一下字符串中一共有多少个空格

2. 根据空格数量创建新字符串的长度 new char[length + spaceLen * 2];

3. 组装新的字符串

class Solution {
    public String replaceSpaces(String S, int length) {
        int spaceLen = 0;
        for (int i = 0; i < length; i++) {
            if (S.charAt(i) == ' ') {
                spaceLen++;
            }
        }
        char[] newStr = new char[length + spaceLen * 2];
        int index = 0;
        for (int i = 0; i < length; i++) {
            char c = S.charAt(i);
            if (c == ' ') {
                newStr[index++] = '%';
                newStr[index++] = '2';
                newStr[index++] = '0';
            }else {
                newStr[index++] = c;
            }
        }
        return new String(newStr);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41389354/article/details/120799366