-
-
Notifications
You must be signed in to change notification settings - Fork 229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
URL反转 #93
Comments
是不能用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) { console.log(reverse(url)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: