Huawei od machine test interview questions

1. HUAWEI machine test 102 question solutions

2. Huawei computer-based test questions

July 30, 2023 19:30~22:00

Computer-based test tips & precautions (must read before the test):

1. Pay attention to the changes in the compilation environment and language selection, and choose the language you are familiar with for the computer-based test.

2. There are 3 questions in the computer-based test, which takes 150 minutes to complete.

3. The difficulty of the questions is: one-star and two-star; 2 one-star questions, 100 points each; 1 two-star question, 200 points; 150 points for passing.

4. Two one-star questions can be viewed by switching between two questions, giving priority to the most certain ones, but once you switch to a two-star question, you cannot switch back to the one-star question!

5. If you are sure to pass the 1-star question and pass 2 full marks, blank test papers are not recommended. You may be just short of points. If the 2-star questions can help you get a few points, you will just pass it!

6. The pass rate of Python and iava is higher, it is said that it is relatively simple, and C/C++ is relatively difficult.

7, C must choose C language to do, do not choose C language

C++ is the question, because C++ written in C language does not necessarily compile and pass! Similarly, C++ must also be done in C++ language! And C must use the standard VC 6.0 compilation environment.

8. Java should use the standard eclipse and the JDK software package that meets the test standards.

9. The computer-based test link is valid for 7 days.

10. Before the computer-based test, you must finish all the questions (more than 100 questions) in the Niuke.com test bank, and take the computer-based test after fully preparing. Because the pass rate of the computer-based test is 20%, once you fail to pass the test, you cannot take the test again within half a year, and you cannot participate in Huawei Other interviews, brush questions links:

https://www.nowcoder.com/ta/huawei。

11. Before the exam, please clean up the computer desktop and close irrelevant windows.

12. Please use the latest version of the chrome browser (version 72 and above) to answer the questions. You need to turn on the camera, screen recording and mobile phone monitoring during the test. If the monitoring is abnormal, your score may be affected. Please adjust the equipment according to the guidelines before answering the questions.

13. Programming questions support local IDE coding and then copy and paste to the test page, without jumping out restrictions. Do not browse other pages except for the local compiler, otherwise risk identification will be carried out and your grades will be affected. (You need to use an IDE that meets the test standards locally to ensure that the local compilation environment is consistent with Niuke.com, and the test must be conducted in the test environment).

14. Scratch paper is allowed during the exam, please prepare paper and pen in advance. It is allowed to leave for a short time during the test, such as going to the toilet, but please control the time of leaving.

15. If you encounter problems such as power outages, network outages, and computer crashes during the exam, you can close the browser and reopen the link to the test paper to continue working on the questions.

16. If you encounter any problems, please contact HR in time.

17. Turn on WiFi in airplane mode.

first question:

topic description

The impoverished woodcutter, Ali Baba, stumbled across the treasure trove of the robber group on his way to cut firewood. There are boxes numbered from 0-N in the treasure trove, and each box has a number on it.

Ali Baba reads a spell number to check whether there are two different boxes in the treasure chest, the numbers on the two boxes are the same, and the absolute value of the difference between the numbers of the two boxes is less than or equal to the spell number,

If there is such a pair of treasure chests, please return the number of the box to the left of the first found pair of treasure chests, if not, return -1

enter description

Enter a string of numbers in the first line, separated by commas, for example: 1,2,3,1

1<=Number of numbers in the string<=100000

-100000 <= each numeric value <= 100000

Enter the spell number on the second line, for example: 3

1<=spell number<=100000

output description

There is such a pair of treasure chests, please return the number of the left box of the first found pair of treasure chests, if it does not exist, return -1

1、

package main
import ( 
"fmt" 
"strings" 
)
func findMatchingBox(nums []int, target int) int { 
boxMap := make(map[int]int)
for i, num := range nums {
    if j, ok := boxMap[num]; ok && i-j <= target {
        return j
    }
    boxMap[num] = i
}

return -1

}
func main() { 
var input string 
fmt.Scan(&input)
numsStr := strings.Split(input, ",")
nums := make([]int, len(numsStr))
for i, numStr := range numsStr {
    fmt.Sscanf(numStr, "%d", &nums[i])
}

var target int
fmt.Scan(&target)

result := findMatchingBox(nums, target)
fmt.Println(result)

}

2、

package main

import (
  "fmt"
  "strings"
)


func findBoxIndex(nums []int, target int) int {
  indexMap := make(map[int]int)


  for i, num := range nums {
    if prevIndex, ok := indexMap[num]; ok && i-prevIndex <= target {
      return prevIndex
    }
    indexMap[num] = i
  }


  return -1
}


func main() {
  var input string
  fmt.Scanln(&input)


  var target int
  fmt.Scanln(&target)


  numStrs := strings.Split(input, ",")
  nums := make([]int, len(numStrs))


  for i, numStr := range numStrs {
    fmt.Sscanf(numStr, "%d", &nums[i])
  }


  result := findBoxIndex(nums, target)
  fmt.Println(result)
}

This program first reads the input string of numbers and spell numbers. Then, it splits the string of numbers into a slice of integers and uses the findBoxIndex function to find the number of the treasure box that satisfies the condition. The findBoxIndex function uses a hash map to record the index of the last occurrence of each number. It iterates over the slice of numbers, and for each number, checks if it already exists in the hash map and the difference from the current index is less than or equal to the spell number. If so, return the index that occurred before; otherwise, add the current index to the hash map. If no treasure chest meeting the condition is found after traversing the entire slice, the function returns -1.

Alibaba looking for a golden treasure chest

The impoverished woodcutter Ali Baba accidentally discovered the treasure chest of the robber group on his way to cut firewood. There are boxes numbered from 0 to N in the treasure trove, and each box has a number on it. There may be a golden treasure chest in the box. .

The golden treasure box satisfies the sum of the numbers of all the boxes before it equal to the sum of the numbers of all the boxes after it; the sum of the numbers on the left part of the first box is defined as 0; the sum of the numbers on the right part of the last treasure box is defined as 0.

Please help Alibaba find the golden treasure chest, and output the number of the first golden treasure chest that meets the conditions. If there is no golden treasure chest, please return -1.

1、

package main
import ( 
"fmt" 
)
func findGoldenBox(nums []int) int { 
n := len(nums)
// 计算总和
totalSum := 0
for _, num := range nums {
    totalSum += num
}

// 左边部分的和
leftSum := 0

// 右边部分的和
rightSum := totalSum

for i := 0; i < n; i++ {
    rightSum -= nums[i]

    if leftSum == rightSum {
        return i
    }

    leftSum += nums[i]
}

return -1

}
func main() { 
var n int fmt.Scan(&n)
nums := make([]int, n)
for i := 0; i < n; i++ {
    fmt.Scan(&nums[i])
}

result := findGoldenBox(nums)
fmt.Println(result)

}

Second question:

Input description: The first line is two numbers M and N, which respectively represent the number of directories and the id of the directory to be queried, 1<=M<=100, 1<=N<=200. The next M lines, each line contains the data of one directory: directory id file size in this directory (list of subdirectory ids), and the subdirectory ids in the subdirectory list are separated by commas.

Output description: The sum of the size of the query directory and its subdirectories.

1. This is a typical tree structure processing problem. We can use depth-first search (DFS) or breadth-first search (BFS) to solve this problem. Below is an example of implementing DFS in Go.

First, we need a data structure to represent a directory, including its id, file size, and a list of its subdirectories. Then we need a function to calculate the sum of the file sizes of a directory and all its subdirectories.

package main


import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)


type Directory struct {
    id     int
    size   int
    children []*Directory
}


var directoryMap = make(map[int]*Directory)


func getSize(dir *Directory) int {
    totalSize := dir.size
    for _, child := range dir.children {
        totalSize += getSize(child)
    }
    return totalSize
}


func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    line := scanner.Text()
    parts := strings.Split(line, " ")
    M, _ := strconv.Atoi(parts[0])
    N, _ := strconv.Atoi(parts[1])


    for i := 0; i < M; i++ {
        scanner.Scan()
        line = scanner.Text()
        parts = strings.Split(line, " ")
        id, _ := strconv.Atoi(parts[0])
        size, _ := strconv.Atoi(parts[1])
        dir := &Directory{
            id:     id,
            size:   size,
            children: []*Directory{},
        }
        directoryMap[id] = dir
        if len(parts) > 2 {
            for _, childIdStr := range strings.Split(parts[2], ",") {
                childId, _ := strconv.Atoi(childIdStr)
                dir.children = append(dir.children, directoryMap[childId])
            }
        }
    }


    fmt.Println(getSize(directoryMap[N]))
}

This program first reads the number of directories and the directory id to be queried, and then reads the data of each directory and stores it in a map. Then, it uses the recursive function getSize to calculate the sum of the file sizes of the directory to be queried and all its subdirectories, and outputs the result.

Note: In this example, we assume that the input data is given in order from parent directory to subdirectory, so that we can immediately find its subdirectory when reading the data of each directory. If the input data is not sorted like this, then we need to read the data of all directories first, and then build the directory tree.

2、

package main


import (
  "fmt"
)


type Directory struct {
  ID       int
  Size     int
  Subdirs  []int
  Children []*Directory
}


func calculateTotalSize(dir *Directory) int {
  totalSize := dir.Size
  for _, subdirID := range dir.Subdirs {
    subdir := dir.Children[subdirID]
    totalSize += calculateTotalSize(subdir)
  }
  return totalSize
}


func main() {
  var m, n int
  fmt.Scanln(&m, &n)


  directories := make([]*Directory, m+1)
  for i := 1; i <= m; i++ {
    var id, size, numSubdirs int
    fmt.Scanln(&id, &size, &numSubdirs)


    subdirs := make([]int, numSubdirs)
    for j := 0; j < numSubdirs; j++ {
      fmt.Scan(&subdirs[j])
    }


    directory := &Directory{
      ID:      id,
      Size:    size,
      Subdirs: subdirs,
    }


    directories[id] = directory
  }


  for i := 1; i <= m; i++ {
    directory := directories[i]
    directory.Children = make([]*Directory, len(directory.Subdirs))
    for j, subdirID := range directory.Subdirs {
      subdir := directories[subdirID]
      directory.Children[j] = subdir
    }
  }


  result := calculateTotalSize(directories[n])
  fmt.Println(result)
}

First build a directory tree based on the input directory data, and then use the recursive function calculateTotalSize to calculate the sum of the size of the given directory and its subdirectories. Finally print out the result.

3、

package main
import ( "fmt" )
type Directory struct { 
ID int 
Size int 
Children []int 
}
func main() { 
var M, N int 
fmt.Scan(&M, &N)
directories := make(map[int]Directory)

for i := 0; i < M; i++ {
    var id, size int
    var children []int

    fmt.Scan(&id, &size)

    var num int
    fmt.Scan(&num)

    for j := 0; j < num; j++ {
        var childID int
        fmt.Scan(&childID)
        children = append(children, childID)
    }

    directory := Directory{
        ID:       id,
        Size:     size,
        Children: children,
    }

    directories[id] = directory
}

result := getDirectorySize(directories, N)
fmt.Println(result)

}
func getDirectorySize(directories map[int]Directory, directoryID int) int { 
directory := directories[directoryID] size := directory.Size
for _, childID := range directory.Children {
    size += getDirectorySize(directories, childID)
}

return size

}

4、

package main


import (
    "bufio"
    "fmt"
    "os"
    "strconv"
)


const N = 1000
func dfs(u int, g [][]int, w []int) int {
    // 初始化为当前目录的大小
    res := w[u]
    for _, v := range g[u] {
        // 获取所有子目录的大小
        res += dfs(v, g, w)
    }
    return res
}


func isDigit(c byte) bool {
    return c >= '0' && c <= '9'
}
func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)


    scanner.Scan()
    m, _ := strconv.Atoi(scanner.Text())


    scanner.Scan()
    idx, _ := strconv.Atoi(scanner.Text())


    // g[i] 表示目录 i 的所有一级子目录
    g := make([][]int, N+1)
    // w[i] 表示目录 i 的文件大小
    w := make([]int, N+1)


    for i := 0; i < m; i++ {
        scanner.Scan()
        x, _ := strconv.Atoi(scanner.Text())


        scanner.Scan()
        w[x], _ = strconv.Atoi(scanner.Text())


        scanner.Scan()
        s := scanner.Text()


        lenS := len(s)
        for j := 0; j < lenS; j++ {
            // 如果不是数字,说明是分隔符
            if !isDigit(s[j]) {
                continue
            }
            t := 0
            k := j
            for k < lenS && isDigit(s[k]) {
                t = t*10 + int(s[k]-'0')
                k += 1
            }
            // t 是其中一个子目录,如此由 x 指向 t ,构造出一个目录树
            g[x] = append(g[x], t)
            j = k - 1
        }
    }


    // 从查询的目录 idx 开始,求出这个目录和其所有子目录的大小
    fmt.Println(dfs(idx, g, w))
}

The third question:

topic

Given an array of strings, each string is composed of lowercase letters and a character pattern is composed of lowercase letters and . and *, identify which strings in the string array can match the character pattern. Match any single character* Match 0 or more arbitrary characters, determine whether the string matches, it is the whole string at the head instead of part of the string

enter

The first line is multiple strings separated by spaces 1 < length of a single string < 100, 1 < number of strings < 100, and the second line is character pattern 1 <= character pattern length <= 50 No need to consider abnormal scenarios

output

When the subscripts (starting from 0) of the matching string in the array match multiple times, the subscripts are sorted in ascending order and separated by a delimiter. If none of them match, output -1

1、

package main


import (
    "fmt"
    "strings"
)


func isMatch(s, p string) bool {
    m, n := len(s), len(p)
    dp := make([][]bool, m+1)
    for i := range dp {
        dp[i] = make([]bool, n+1)
    }
    dp[0][0] = true
    for i := 0; i <= m; i++ {
        for j := 1; j <= n; j++ {
            if p[j-1] == '*' {
                dp[i][j] = dp[i][j-2] || (i > 0 && (s[i-1] == p[j-2] || p[j-2] == '.') && dp[i-1][j])
            } else {
                dp[i][j] = i > 0 && (s[i-1] == p[j-1] || p[j-1] == '.') && dp[i-1][j-1]
            }
        }
    }
    return dp[m][n]
}


func findMatchedStrings(strs []string, pattern string) string {
    var res []int
    for i, str := range strs {
        if isMatch(str, pattern) {
            res = append(res, i)
        }
    }
    if len(res) == 0 {
        return "-1"
    }
    return strings.Trim(strings.Replace(fmt.Sprint(res), " ", ",", -1), "[]")
}

func main() {
    var strs []string
    var pattern string
    fmt.Scan(&strs)
    fmt.Scan(&pattern)
    fmt.Println(findMatchedStrings(strs, pattern))
}

In this implementation, the isMatch function is used to judge whether a string can match a given character pattern. The implementation of this function refers to the solution to question 10 on LeetCode.

The findMatchedStrings function is used to find all subscripts of strings that can match a given character pattern. Returns -1 if no string matches the character pattern. The implementation of this function uses functions from the strings and fmt packages to format the output.

2、

package main


import (
  "fmt"
  "strings"
)


func matchStrings(stringsArr []string, pattern string) string {
  var result []string
  for i, str := range stringsArr {
    if isMatch(str, pattern) {
      result = append(result, fmt.Sprintf("%d", i))
    }
  }


  if len(result) > 0 {
    return strings.Join(result, " ")
  }
  return "-1"
}


func isMatch(str, pattern string) bool {
  if len(str) != len(pattern) {
    return false
  }


  for i := 0; i < len(str); i++ {
    if pattern[i] != '.' && pattern[i] != '*' && str[i] != pattern[i] {
      return false
    }
  }


  return true
}


func main() {
  var stringsArr []string
  var pattern string


  fmt.Print("Enter the strings separated by space: ")
  fmt.Scanf("%s", &stringsArr)


  fmt.Print("Enter the pattern: ")
  fmt.Scanf("%s", &pattern)


  result := matchStrings(stringsArr, pattern)
  fmt.Println("Output:", result)
}

This program first reads the input string array and character pattern, and then calls the matchStrings function to match. In the matchStrings function, it iterates through the array of strings and checks whether each string matches the given pattern of characters, and if so, adds the index of that string to the resulting array. Finally, it converts the resulting array to a string and returns it.

The isMatch function is used to check whether a single string matches the given character pattern. It first checks whether the string length is the same as the character regular length, and then compares character by character. Returns false if the character in the character pattern is not . or * and does not match a character in the string.

3. Regular expressions can be used to match strings. First, the character pattern is converted into a regular expression format, and then the string array is traversed one by one, and the regular expression is used for matching.

package main


import (
    "fmt"
    "regexp"
    "strings"
)


func main() {
    var strs []string
    var pattern string


    // 读取输入
    fmt.Scan(&strs)
    fmt.Scan(&pattern)


    // 将字符规律转换为正则表达式的格式
    pattern = strings.ReplaceAll(pattern, ".", "\\.")
    pattern = strings.ReplaceAll(pattern, "*", ".*")


    // 构建正则表达式对象
    reg := regexp.MustCompile("^" + pattern + "$")


    // 遍历字符串数组,进行匹配
    matches := make([]int, 0)
    for i, str := range strs {
        if reg.MatchString(str) {
            matches = append(matches, i)
        }
    }


    // 输出匹配的字符串下标
    if len(matches) > 0 {
        fmt.Println(strings.Trim(strings.Join(strings.Fields(fmt.Sprint(matches)), " "), "[]"))
    } else {
        fmt.Println(-1)
    }
}

Input example:

abc def ghi

a.*c

Example output:

0

Input example:

abc def ghi

a.*d

Example output:

-1

3. Huawei technical interview questions

longest repeating substring

describe

Definition A repeated string is formed by concatenating two identical strings at the beginning and end. For example: "abcabc" is a repeated string of length 6 because it is formed by concatenating two "abc" strings; "abcba" is not a repeated string because it cannot be formed by concatenating two identical strings.

Given a string, return the length of its longest repeated substring.

Returns 0 if there are no repeated character substrings.

The definition of a substring in this question is a continuous interval in a string.

Data range: The length of the string is not greater than 10^3, and the string must be composed of lowercase letters.

Example 1

Enter: "ababc"

Return value: 4

illustrate:

abab is the longest repeated character substring with a length of 4

Example 2

Enter: "abcab"

return value: 0

illustrate:

The string has no repeating character substrings

Implemented using double pointers

Ideas:

  1. Traversing the string, starting from each character, finds the length of the longest repeated substring starting from that character.
  2. For each starting point, use double pointers, one pointer starts from the starting point, and one pointer starts from the next position of the starting point, and compares whether the characters pointed by the two pointers are the same, until a different character is found , record the substring length at this time.
  3. Update the length of the longest repeated substring.
  4. Returns the length of the longest repeated substring.

The code is implemented as follows:

func longestDupSubstring(s string) int {
    n := len(s)
    if n == 0 {
        return 0
    }
    maxLen := 0
    for i := 0; i < n; i++ {
        for j := i + 1; j < n; j++ {
            if s[i] == s[j] {
                k := 1
                for i+k < n && j+k < n && s[i+k] == s[j+k] {
                    k++
                }
                if k > maxLen {
                    maxLen = k
                }
            }
        }
    }
    return maxLen
}

Complexity analysis:

  • Time complexity: O(n^3), where n is the length of the string. Two layers of loops traverse the string, and an inner layer of loops is used to find repeated substrings.
  • Space complexity: O(1). No extra space is used.

Optimize time complexity

Optimizing the time complexity refers to improving the algorithm or data structure to make the time complexity of the algorithm lower, thereby improving the execution efficiency of the algorithm.

Common methods for optimizing time complexity are:

  1. Use more efficient algorithms: Solve problems by finding better algorithms, such as using quick sort instead of bubble sort, etc.
  2. Reduce the number of loops: Avoid unnecessary loops and minimize the number of loops.
  3. Use space for time: reduce the time complexity of the algorithm by using additional data structures, such as using hash tables to improve the efficiency of lookups.
  4. Pruning: In the search algorithm, the search space is reduced through the pruning strategy, thereby reducing the time complexity of the algorithm.
  5. Dynamic programming: By decomposing the problem into sub-problems and saving the solutions of the sub-problems, avoiding repeated calculations, thereby reducing the time complexity of the algorithm.
  6. Optimization of graph algorithms: For example, use Dijkstra algorithm instead of brute force search algorithm to solve the shortest path problem.

It should be noted that optimizing the time complexity often needs to be considered at the early stage of algorithm design, rather than optimizing during the coding process. At the same time, optimizing the time complexity may not always lead to the optimal solution, and sometimes it is necessary to balance the balance between time complexity and space complexity.

Implemented using sliding windows and hash tables

To realize the problem of the longest repeated substring and optimize the time complexity, the method of sliding window and hash table can be used.

Specific steps are as follows:

  1. Define two pointers left and right, which represent the left and right borders of the sliding window respectively.
  2. Use a hash table to record the latest position where each character occurs.
  3. Initialize the length maxLen of the longest repeated substring to 0.
  4. Traversing the string, when the right pointer reaches the end of the string, the loop ends.
  5. If the current character already exists in the hash table, and its latest position is greater than or equal to the left pointer, update the left pointer to the next position of the character's latest position.
  6. Update maxLen to be the maximum value of the length of the current window and maxLen.
  7. Update the latest position of the current character as the right pointer.
  8. Returns maxLen as the length of the longest repeating substring.

Here is the code implemented using Golang:

func findLongestDuplicateSubstr(s string) int {
    n := len(s)
    if n <= 1 {
        return 0
    }
    left, right := 0, 1
    maxLen := 0
    lastIndex := make(map[byte]int)
    for right < n {
        if lastIndex[s[right]] >= left {
            left = lastIndex[s[right]] + 1
        }
        maxLen = max(maxLen, right-left+1)
        lastIndex[s[right]] = right
        right++
    }
    return maxLen
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

The time complexity of this algorithm is O(n), where n is the length of the string.

Implemented using dynamic programming

Golang realizes the length of the longest repeated substring, dynamic programming

This is a classic dynamic programming problem. Using Golang to realize the length of the longest repeated substring can adopt the idea of ​​dynamic programming:

  1. Define a two-dimensional array dp, dp[i][j] represents the length of the longest repeated substring ending with the i-th character and the j-th character of the string s.
  2. Initialize the first row and first column of the dp array to 0, because the length of the substring ending with the first character is 0.
  3. Traverse each character of the string s, and maintain a maximum length maxLen, which is used to record the length of the longest repeated substring currently found.
  4. If the i-th character of s is equal to the j-th character (i ≠ j), then dp[i][j] = dp[i-1][j-1] + 1, indicating that the current character can be compared with the previous character form longer repeating substrings.
  5. Update maxLen to the larger value of dp[i][j] and maxLen.
  6. Finally, just return maxLen.

Here is a code example implemented in Golang:

func LongestRepeatingSubstring(s string) int {
    n := len(s)
    dp := make([][]int, n+1)
    for i := 0; i <= n; i++ {
        dp[i] = make([]int, n+1)
    }
    maxLen := 0
    for i := 1; i <= n; i++ {
        for j := i+1; j <= n; j++ {
            if s[i-1] == s[j-1] {
                dp[i][j] = dp[i-1][j-1] + 1
                maxLen = max(maxLen, dp[i][j])
            }
        }
    }
    return maxLen
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

When in use, call LongestRepeatingSubstringthe function and pass in the string s to be calculated to get the length of the longest repeated substring.

Implemented using the KMP algorithm

Golang realizes the length of the longest repeated substring, KMP

To use the KMP algorithm to achieve the length of the longest repeated substring, you need to understand the principle of the KMP algorithm.

The KMP algorithm is an algorithm for string matching. Its core idea is to construct a next array by preprocessing the pattern string (that is, the substring to be matched), which is used to quickly skip the matched part during the matching process. .

The following is a code example of the KMP algorithm that uses Golang to realize the length of the longest repeated substring:

func LongestRepeatingSubstring(s string) int {
    n := len(s)
    // 构建next数组
    next := make([]int, n)
    for i := 1; i < n; i++ {
        j := next[i-1]
        for j > 0 && s[i] != s[j] {
            j = next[j-1]
        }
        if s[i] == s[j] {
            j++
        }
        next[i] = j
    }
    // 找到最长重复子串的长度
    maxLen := 0
    for i := 1; i < n; i++ {
        maxLen = max(maxLen, next[i])
    }
    return maxLen
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

When in use, call LongestRepeatingSubstringthe function and pass in the string s to be calculated to get the length of the longest repeated substring.

Note that the implementation of the KMP algorithm here is used to calculate the length of the longest repeated substring, not for string matching. So when constructing the next array, s[i] and s[j] are compared each time, not s[i] and s[j+1].

Guess you like

Origin blog.csdn.net/niwoxiangyu/article/details/132240984