HUAWEI OD machine test real test JavaScript implementation [Find the longest common substring in two strings a, b] [Niu Ke practice questions]

insert image description here

1. Topic description

Find the longest common substring of two strings a, b. If there are more than one, output the one that appears first in the shorter string.

Note: Definition of substring: A string formed by deleting the prefix and suffix (or not) from a string. Please separate from the concept of "subsequence"!

Data range: string length 1≤length≤300.

2. Enter description

Enter two strings.

3. Output description

Returns repeated occurrences of characters.

4. Problem-solving ideas

  1. First read the two input strings;
  2. Determine which string is shorter, use it as a short string, and the other string as a long string;
  3. Get the length of short string and long string;
  4. Initialize the variables maxLen and start, which are used to record the length and starting position of the longest common substring respectively;
  5. Use two layers of loops, the outer loop traverses the short string, and the inner loop traverses the substrings in the short string;
  6. In each inner loop, judge whether the current substring is a substring of a long string, and compare whether its length is greater than the maximum length of the previous record;
  7. If the conditions are met, update the maximum length maxLen and the starting position start;
  8. After the loop ends, the longest common substring is extracted from the short string according to the maximum length and the starting position, and output.

5. JavaScript algorithm source code

 

Supongo que te gusta

Origin blog.csdn.net/guorui_java/article/details/131196928
Recomendado
Clasificación