Home > Web Front-end > JS Tutorial > body text

Compute matching substrings in JavaScript

PHPz
Release: 2023-08-23 23:21:03
forward
1349 people have browsed it

在 JavaScript 中计算匹配子字符串

The ability to accurately calculate matching substrings in a given string is a key skill in JavaScript programming, as it enables developers to efficiently analyze and manipulate text data. This article delves into the world of string manipulation and explores the complexities of calculating matching substrings in JavaScript, using a series of little-known techniques. By clarifying the underlying logic and employing these unconventional methods, developers can gain a deeper understanding of how to efficiently count occurrences of specific substrings, allowing them to extract meaningful insights from text data. Join us on this inspiring journey as we unlock the potential of JavaScript's power and expand our rich vocabulary to master the art of calculating matching substrings.

Problem Statement

We need a JavaScript function that calculates a subsequence in a given string and takes a string input named "str" ​​and an array of string inputs named "arr". The goal is to examine each element in "arr" and determine the number of strings that are subsequences of "str". A subsequence is a string formed by removing characters from the original string while maintaining the relative order of the remaining characters. The function should carefully compare each element in "arr" and "str" ​​and determine whether it can be constructed by removing characters from "str". It will then return an integer representing the count of qualified subsequences found in "str".

Example input -

str = 'abracadabra';
arr = ['a', 'bra', 'cad', 'dab'];
Copy after login

Example output -

Output =4;
Copy after login

Output description -

In the given input, the string "str" ​​is "abracadabra" and the array "arr" contains ['a', 'bra', 'cad', 'dab'].

Analyzing each element of "arr", we find that "a", "bra", "cad" and "dab" are all subsequences of "str". Therefore, the count of the subsequence is 4, which is the expected output.

method

In this article we will see a number of different ways to solve the above problems in JavaScript -

  • Brute force cracking method

  • Double pointer method

Method 1: Brute force cracking

The brute force method of computing valid subsequences involves generating all possible subsequences of a string and checking their presence in an array. We iterate over each string, generating subsequences recursively or using bitwise operations, and compare them to the array elements. The counter is incremented every game, giving a total count. This method is computationally expensive for larger inputs, so alternative algorithms such as dynamic programming provide more optimal solutions.

Example

This code implements a recursive algorithm to count the number of subsequences of a given string (str) in an array of strings (arr). The countSubsequences function initializes a count variable to keep track of valid subsequences. The generateSubsequences function generates all possible subsequences by iterating over the input string and checking whether each subsequence is present in the array. The recursive call is made to explore different possibilities of including or excluding characters. The main function call generates a subsequence starting from the beginning of the string. The count variable is returned as the final result. Example Usage demonstrates the use of this function with sample strings and string arrays. The results are stored and printed to the console.

function countSubsequences(str, arr) {
   let count = 0;
 
   // Generate all possible subsequences of the input string
   function generateSubsequences(sub, index) {
      if (index === str.length) {
         // Check if the subsequence exists in the array
         if (arr.includes(sub)) {
            count++;
         }
         return;
      }
 
      // Include the current character in the subsequence
      generateSubsequences(sub + str[index], index + 1);
 
      // Exclude the current character from the subsequence
      generateSubsequences(sub, index + 1);
   }
 
   // Start generating subsequences from the beginning of the string
   generateSubsequences("", 0);
 
   return count;
}
 
// Example usage:
const str = "abcde";
const arr = ["a", "ab", "bd", "abc", "acde", "eab"];
const result = countSubsequences(str, arr);
console.log(result);
Copy after login

Output

The following is the console output -

5
Copy after login
Copy after login

Method 2: Two-pointer method

This algorithm iterates through each string in the array and uses two pointers, one designated to the given string and the other to the string currently being examined. These pointers are initially located at the starting character of their corresponding strings and then advance forward until the end of either string is encountered. Each time a valid subsequence is determined, the numeric indicator is incremented. Finally, the algorithm provides the numerical value of the indicator as the final result.

Example

The function countValidSubsequences takes a string array (arr) and a target string (target) as parameters. It iterates over each string in arr and compares its characters to those in target using a nested loop. If the characters match, the index is incremented; if they don't match, just the target's index is incremented. If the entire string is a valid subsequence, the count is incremented. After iterating through all strings in arr, the function returns the final count.

function countValidSubsequences(arr, target) {
   let count = 0;
 
   for (let i = 0; i < arr.length; i++) {
      const current = arr[i];
      let j = 0;
      let k = 0;
 
      while (j < current.length && k < target.length) {
         if (current[j] === target[k]) {
            j++;
            k++;
         } else {
            k++;
         }
      }
 
      if (j === current.length) {
         count++;
      }
   }
 
   return count;
}
 
// Example usage: 
const str = "abcde"; 
const arr = ["a", "ab", "bd", "abc", "acde", "eab"]; 
const result = countValidSubsequences(arr, str); 
console.log(result);
Copy after login

Output

The following is the console output -

5
Copy after login
Copy after login

in conclusion

Ultimately, this exploration of matching substring counting in JavaScript has uncovered a number of clever techniques that can be used to accomplish this task efficiently. By employing various algorithms and taking advantage of the language's rarely used features, programmers can design elegant and resourceful solutions. It must be acknowledged that the complexity of substring matching requires careful consideration of edge cases and potential performance impacts. However, with these newfound insights, developers can go beyond traditional approaches and leverage the full potential of JavaScript to cleverly enumerate and manipulate substrings. Overall, the in-depth knowledge shared in this article enables programmers to improve their coding abilities and unlock new dimensions of substring counting in JavaScript.

The above is the detailed content of Compute matching substrings in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!