Location>code7788 >text

2024-08-03: In go, given an array of strings `words` starting at 0, we define a boolean function called `isPrefixAndSuffix` that takes two string arguments `str1` and

Popularity:728 ℃/2024-08-03 18:08:48

2024-08-03: Given an array of strings starting from 0, using go languagewords

We define a file namedisPrefixAndSuffix Boolean function which takes two string argumentsstr1 cap (a poem)str2

(coll.) fail (a student)str1 at the same timestr2 The function returns the prefix and suffix of thetrueOtherwise, returnfalse

For example.isPrefixAndSuffix("aba", "ababa") come (or go) backtrue

Because "aba" is both a prefix and a suffix of "ababa," whileisPrefixAndSuffix("abc", "abcd") come (or go) backfalse

Our goal is to return the number of subscript pairs (i, j) that satisfy the condition as an integer.

which satisfies thei < j both (... and...)isPrefixAndSuffix(words[i], words[j]) because oftrue

Input: words = ["a", "aba", "ababa", "aa"].

Output: 4.

EXPLANATION: In this example, the subscript pairs for counting are included:

i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.

i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.

i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.

i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.

Therefore, the answer is 4.

Answer 2024-08-03:

chatgpt

Title from leetcode3045.

The broad steps are as follows:

1 Defining FunctionsisPrefixAndSuffix(str1, str2): Implement a function that determinesstr1 is or isn'tstr2 The prefixes and suffixes of the

  • probestr1 Is the length of thestr2 The length of the If so, return directlyfalse

  • recognizestr2 Does the prefix of thestr1 Same.

  • recognizestr2 Does the suffix of thestr1 Same.

  • If both of the above conditions are met, returntrueOtherwise, returnfalse

2.Iterating over an array of stringswords

  • Two nested loops are used, with the outer loop set toiThe following is an example of a traversal from 0 tolen(words)-1The inner loop is set tojnotice fromi+1 Iterate overlen(words)-1. This ensures thati < j

3.call (programming)isPrefixAndSuffix function (math.): In each pair of(i, j) In theisPrefixAndSuffix(words[i], words[j])

  • If the function returnstrueThe counter is incremented by 1.

4.Returns the value of the counter: Eventually, the value of the counter is returned, which is the number of subscript pairs that meet the condition.

total time complexity

  • Outer layer cycling awayn times, with the inner loop starting ati+1 until (a time)n, the worst-case scenario isO(n)

  • For each pair(i, j)CallisPrefixAndSuffix It needs to be inO(m) The comparison of strings is performed in time, wherem is the length of the prefix or suffix.

  • Therefore, the total time complexity isO(n^2 * m)whichm is the maximum length of the string.

Total extra-space complexity

  • This algorithm uses a small amount of extra space to store counters and some local variables of the function, so the extra space complexity isO(1)
  • String comparisons within the function require no additional storage, using only constant space to store temporary variables, with the main storage body in the inputwords Center.

In summary, the time complexity isO(n^2 * m), the additional space complexity isO(1)

The full Go code is below:

existpackage main

import (
	"fmt"
)

func countPrefixSuffixPairs(words []string) (ans int64) {
	type pair struct{ x, y byte }
	type node struct {
		son map[pair]*node
		cnt int
	}
	root := &node{son: map[pair]*node{}}
	for _, s := range words {
		cur := root
		for i := range s {
			p := pair{s[i], s[len(s)-1-i]}
			if [p] == nil {
				[p] = &node{son: map[pair]*node{}}
			}
			cur = [p]
			ans += int64()
		}
		++
	}
	return
}


func main() {
	words:=[]string{"a","aba","ababa","aa"}
	(countPrefixSuffixPairs(words))
}

在这里插入图片描述

The full Python code is below:

# -*-coding:utf-8-*-

class TrieNode:
    def __init__(self):
         = {}
         = 0

def count_prefix_suffix_pairs(words):
    root = TrieNode()
    ans = 0

    for s in words:
        current = root
        length = len(s)
        
        for i in range(length):
            p = (s[i], s[length - 1 - i]) # Using tuples to represent prefix and suffix character pairs
            if p not in :
                [p] = TrieNode()
            current = [p]
            ans += # Count the number of logarithms that satisfy the condition
         += 1 # Update the count of the current node

    return ans

if __name__ == "__main__":
    words = ["a", "aba", "ababa", "aa"]
    print(count_prefix_suffix_pairs(words))

在这里插入图片描述