String duplication removal and string inversion in JS algorithm tutorial

  • 2021-10-13 06:36:02
  • OfStack

1. String de-duplication

Speaking of string deduplication, we will think of array deduplication in the first time, so we can convert strings into arrays, then deduplicate arrays, and splice them into strings after deduplication. Here are two methods of string deduplication. Next, we will look at the code.

Method 1:

Logical steps:

1. Use the split or ES6 expansion operator... to cut the string into an array

2. Use Set data deconstruction of ES6, which is similar to an array, but the values of its members are only 1, and use new to create

3. Use join splicing for the deduplicated array


let str = '11223344aabbcc'
function strSeparate(s) {
 return [...new Set([...s])].join('');
 // or return [...new Set(s.split(''))].join('')
}
console.log(strSeparate(str))

Method 2:

Logical steps:

The logical steps of the second method are different from those of the first method only in the second step. Both steps 1 and 3 are to convert strings into arrays, remove duplicates from arrays, and then splice them into strings.


function strSeparate(s) {
 //  Using the expansion operator, a string is converted to an array 
 s = ...str;
 let arr = [];
 for(let i = 0; i < s.length; i++) {
  if(arr.indexOf(s[i]) == -1) {
   arr.push(s[i])
  }
 }
 return arr.join('');
}

2. String inversion

Strings Anyway, the easiest thing I can think of is to use the reverse method of arrays, so I still need to cut strings into arrays, then reverse the arrays, and then splice them.


let str = 'abcdefg'
function strReverse(s) {
 return [...s].reverse().join('');
}
// or
function reverse(s) {
 return s.split('').reverse().join('');
}

As for the string transfer method there are many, I also see a lot of online, still think the above two most simple, if you have any better method, you can leave a message can also be private, we learn from each other

Summarize


Related articles: