How to use Sorting In Javascript
Using sorting, the approach generates all possible combinations of four substrings, sorts them, and checks if adjacent substrings are distinct. If all adjacent substrings are distinct, the string can be split into four distinct strings.
Example:
function canSplitIntoFourDistinctStrings(str) {
let substrings = [];
let n = str.length;
for (let i = 1; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (let k = j + 1; k < n; k++) {
let first = str.slice(0, i);
let second = str.slice(i, j);
let third = str.slice(j, k);
let fourth = str.slice(k);
substrings = [first, second, third, fourth];
substrings.sort();
if (substrings[0] !== substrings[1] && substrings[1] !== substrings[2]
&& substrings[2] !== substrings[3]) {
return true;
}
}
}
}
return false;
}
console.log(canSplitIntoFourDistinctStrings("abcdefgh")); // true
console.log(canSplitIntoFourDistinctStrings("abcdabcdabcdabcd")); // false
Output
true true
JavaScript Program to Check if Given String can be Split into Four Distinct Strings
A string can be split into four distinct strings by identifying specific delimiters or patterns within the original string and extracting substrings based on these divisions, resulting in four separate and non-overlapping text segments. In this article, we will check if a given string can be split into four distinct strings.
Table of Content
- Using Regular Expression
- Using Recursive Method
- Using The Length Property
- Using Sorting
- Using Substring Method and Set
Contact Us