Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

URL反转

Sunny-117 opened this issue · comments

commented
URL反转

是不能用split 和 join那题吗

        let url = 'www.baidu.toutiao.com'
        function reverseURL(str) {
            const len = str.length
            let i = j = 0
            let res = ''
            while(j < len){
                if(str[j] === '.'){
                    res = '.' + str.slice(i,j) + res
                    i = ++j
                }else {
                    j++
                }
            }
            res = str.slice(i, j) + res
            console.log(res);
        }
        console.log(reveerseURL(url)) // 'com.taobao.baidu.www'
// 那我这样也不算违规吧...
Array.prototype._join = function(char){
    let res = "";
    for(let i = 0; i < this.length; ++i){
        if(i === this.length - 1){
            res += this[i];
        }else{
            res += this[i] + char;
        }
    }
    return res;
}

Array.prototype._reverse = function(){
    for(let i = 0, j = this.length - 1; i < j; ++i, --j){
        [this[i], this[j]] = [this[j], this[i]];
    }
    return this;
}

String.prototype._split = function(char){
    const res = [];
    let temp = "";
    for(let i = 0; i < this.length; ++i){
        if(this[i] === char){
            res.push(temp);
            temp = "";
        }else{
            temp += this[i];
        }
    }
    if(temp){
        res.push(temp);
    }
    return res;
}

function reverseURL(url) {
    return url._split(".")._reverse()._join(".");
}
console.log(reverseURL(url))
// 时间复杂度O(n) 空间复杂度O(1)
function reverseURL(url) {
    const arr = [];
    let res = "";
    for(let i = url.length - 1; i >= 0; --i){
        url[i] !== "." && (res = url[i] + res);
        if(i === 0 || url[i] === "."){
            arr.push(res);
            res = "";
        }
    }

    for(let i = 0; i < arr.length; ++i){
        res += arr[i];
        if(i !== arr.length - 1){
            res += "."
        }
    }
    return res;
}
var str = "www.baidu.taobao.com";
var reversedStr = '';
var temp = '';

for (let i = str.length - 1; i >= 0; i--) {
    if (str[i] === '.') {
        reversedStr += temp + '.';
        temp = '';
    } else {
        temp = str[i] + temp;
    }
}

reversedStr += temp;

console.log(reversedStr);

let url = 'www.baidu.toutiao.com'

function reverse(str) {
let _str = '';
let _item = '';
for(var i = 0; i < str.length; i++) {
if(str[i] != '.') {
_item = _item+str[i]
} else {
if(_str) {
_str = _item +'.' + _str;
} else {
_str = _item;
}
console.log('_str', _str);
_item = '';
}
}
return _item + '.' + _str;
}

console.log(reverse(url));