URL反转
Sunny-117 opened this issue · comments
Sunny commented
URL反转
Nasuke commented
是不能用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'
veneno_o commented
// 那我这样也不算违规吧...
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))
veneno_o commented
// 时间复杂度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;
}
kangkang123269 commented
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);
yanglongfei commented
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));