LeetCode Is Subsequence Greedy Algorithm(golang)

Problem
在这里插入图片描述
Basics
Greddy Algorithm
The greedy algorithm, which means that when you solve a problem, you always make what seems to be the best choice at the moment. In other words, instead of thinking about the overall optimal solution, the algorithm gives you a partial optimal solution in some sense

The idea of algorithm
1.Build a mathematical model to describe the problem
2.Divide the problem solved into subproblems
3.The local optimal solution of each subproblem is obtained by solving each subproblem
4.The local optimal solution of the subproblem is synthesized into a solution of the original solution

which problem can be soved by Greedy?
1.There is an optimal way to solve the problem
2.As the algorithm progresses, two other collections will be accumulated: one containing candidates that have been considered and selected, and the other containing candidates that have been considered but discarded
3.There is a function that checks whether a collection of candidate objects provides the answer to the problem regardless of whether the solution at this point is optimal
4.There is also a function that checks whether a set of candidate objects is feasible, that is, whether it is possible to add more candidates to the set to get a solution that is the same as the previous function, regardless of the optimality of the solution
5.The selection function can indicate which of the remaining candidates is most likely to form the solution to the problem

Analysis Process
This question asks whether S is a subsequence of T, so as long as any way of ss appearing in T can be found,ss can be considered a subsequence of T
And when we match from front to back, it turns out that every time we covet the preceding character, it’s the best decision
Assume that the current character c needs to be matched, and that the position of the character c in t is x1and x2(x1 <x2), then the greedy x1 is the optimal solution, because x1 can also be picked after x2, and through x1 and x2 is more likely to match successfully
In this way, we initialize two Pointers i and j to the initial positions of s and t, respectively, and each time we make a greedy match,iand j both move right to match the next position of s, and j moves right to match the next position of s if the match fails,i remains unchanged, and try to match s with the next character of t
Finally, if i moves to the end of s, ss is a subsequence of t

Code

func isSubsequence(s string, t string) bool {
    n, m := len(s), len(t)  //the length of s and t
    i, j := 0, 0            //define two pointers,i reprents the shorter string , j reprents the longer string
    for i < n && j < m {    
        if s[i] == t[j] {   if the value of s[i] equals t[i],the pointer i moves right ,to the end
            i++
        }
        j++       //if not ,the pointer j moves right
    }
    return i == n
}

猜你喜欢

转载自blog.csdn.net/qq_46595591/article/details/107731436