How to use Recursive Method In Javascript
Here we are using recursive approach to determine if a given string can be split into four distinct substrings. It checks if a substring can be split further and maintains distinctness, returning “Yes” if possible, “No” otherwise.
Example: In this example we are using above mentioned approach.
function isDistinct(s1, s2) {
return s1.localeCompare(s2) !== 0;
}
function distinctStrings(s) {
if (s.length < 4) {
return false;
}
function splitAndCheck(s, val) {
if (val === 0) {
return true;
}
for (let i = 1; i < s.length; i++) {
const s1 = s.substring(0, i);
const s2 = s.substring(i);
if (isDistinct(s1, s2)) {
if (splitAndCheck(s2, val - 1)) {
return true;
}
}
}
return false;
}
return splitAndCheck(s, 4);
}
const inputStr = "w3wiki";
if (distinctStrings(inputStr)) {
console.log("Yes");
} else {
console.log("No");
}
Output
Yes
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