-
-
Notifications
You must be signed in to change notification settings - Fork 241
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # 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)); |
function toreverse(str) {
let st = "";
let reg = /[a-z]+./g;
let arr = str.match(reg);
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i][arr[i].length - 1] === ".") {
arr[i] = arr[i].slice(0, arr[i].length - 1);
}
st += arr[i] + ".";
}
return st.slice(0, st.length - 1);
}
let url = "www.baidu.toutiao.com";
console.log(toreverse(url)); |
# for free
to join this conversation on GitHub.
Already have an account?
# to comment
No description provided.
The text was updated successfully, but these errors were encountered: