zoukankan      html  css  js  c++  java
  • LeetCode --- 字符串系列 --- URL化

    URL化

    题目

    URL化。

    编写一种方法,将字符串中的空格全部替换为%20。

    假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。

    (注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)

    提示:

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


    示例

    示例 1:
    
    输入:"Mr John Smith    ", 13
    输出:"Mr%20John%20Smith"
    
    示例 2:
    
    输入:"               ", 5
    输出:"%20%20%20%20%20"
    

    来源:力扣(LeetCode)

    链接:https://leetcode-cn.com/problems/string-to-url-lcci

    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


    解题思路

    1、直接截取 0 到 length 长度的字符串
       使用 正则 全局替换 空格 成 %20
    

    力扣较好题解

    1、直接截取 0 到 length 长度的字符串
       使用 浏览器 encodeURIComponent/encodeURI 直接转换
    

    题解

    // 用时较长,内存消耗较大
    执行用时: 108 ms
    内存消耗: 67.6 MB
    
    let replaceSpaces = function(S, length) {
        // 直接截取 0 到 length 长度的字符串
        // 使用 正则 全局替换 空格 成 %20
        return S.slice(0, length).replace(/s/g, '%20')
    }
    

    力扣较好题解

    // 用时较好,内存消耗较好
    执行用时: 88 ms
    内存消耗: 43.4 MB
    
    let replaceSpaces = function(S, length) {
        // 直接截取 0 到 length 长度的字符串
        // 使用 浏览器 encodeURIComponent/encodeURI 直接转换
        return encodeURIComponent(S.slice(0, length));
        return encodeURI(S.slice(0, length));
    }
    

  • 相关阅读:
    requireJS搭建
    html启动本地.exe文件
    自定义input[type="checkbox"]的样式
    使用rem单位时css sprites的坑
    visibility API
    css动画
    去除ios端输入框的弹出
    *java类的生命周期
    处理高并发,防止库存超卖
    java注解的使用
  • 原文地址:https://www.cnblogs.com/linjunfu/p/12789071.html
Copyright © 2011-2022 走看看