字符串组合,要求连续

139 阅读1分钟

题:把一个字符串,这里举例‘abc’进行排列组合 a b c ab bc abc

JB3OKW)OKVSH($E73}ZCY.jpg

刚开始我一直是 a ab abc b bc abc 这样写的,一直没发现规律,感觉这样的思路写逻辑写不太出来,按照上面的图思路就清晰了。

参考的是这样写的

let t = 'abc'
// as是一个不可以重复的数组
let as=new Set();

let flag=1;
// 左指针
let l=0;
// 右指针
let r=flag-1;
// 定义一个数组
let temp=new Array();
// 右指针-左指针 !== t.length
while(r-l!=t.length){
    debugger
    if(r==t.length){
        flag++;
        r=flag-1;
        l=0;
        temp.sort();
        temp.forEach((item)=>{
            as.add(item);
        });
        temp=[];
    }
    temp.push(t.slice(l,r+1));
    l++;
    r++;
}
 
let ar='';
as.forEach((item)=>{
        ar=ar+item+' ';
     
})
console.log(ar);

我是这样写的

let str = 'abcabc'
let left = 0
let right = 1
// 计算执行了几个来回,刚开始是0来回
let count = 0
// 01 12 23  02 13 03
let list = []

while(count !== str.length) {
  if(right == str.length) {
    count += 1
    list.push(str.slice(left,right))
    left = 0 
    right = 1 + count
  } else {
    list.push(str.slice(left,right))
    left++
    right++
  }
}
// 使用new Set去重
list = new Set(list)
console.log(list)

写的时候的思路

let str = 'abc'
let left = 0
let count = 0
let right = 1
let list = []



// 这样写第三次进不来了,假设用count就可以了
while(right - left !== str.length) {
  if(right == str.length) {
    count += 1
    list.push(str.slice(left,right))
    left = 0 
    right = 1 + count
    debugger
  } else {
    list.push(str.slice(left,right))
    left++
    right++
  }
}


list = new Set(list)
console.log(list)