1. 程式人生 > >leetcode -- 392. Is Subsequence 【貪心演算法 + 雙指標 + 無後效性】

leetcode -- 392. Is Subsequence 【貪心演算法 + 雙指標 + 無後效性】

題目

Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace"

is a subsequence of "abcde" while "aec" is not).

Example 1:
s
= "abc", t = "ahbgdc"

Return true.

Example 2:
s
= "axc", t = "ahbgdc"

Return false.

Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?

題意

關鍵概念:一個字串的子序列是指,從最初的字串中刪除一些字元生成一個新的字串,並且不改變剩下字元的相對順序。

分析及解答

說明:

需要思考
1.為何這個問題適合使用貪心策略?
2.如何將子問題與原問題 通過貪心策略聯絡起來?

分析:

  1. 主要變數】問題中涉及的兩個主要變數,一個源串,一個是目標串。
  2. 變數有序性】源串以及目標串都具有有序性,即我不能利用排序帶來的優化
  3. 問題分解+無後效性】分解的子問題之間應該具有一定的獨立性(無後效性),兩個指標標識的位置意味著將問題分解成了新的源串和目標串,後面的子問題中不需要考慮之前的子問題的內容,即後面的子問題不需看到之前的問題。
public boolean isSubsequence(String s, String t) {
		int i,j;
		for(i=0,j=0;i < s.length() && j < t.length();){
			if(s.charAt(i) == t.charAt(j)){
				i++;
				j++;
			}else{
				j++;
			}
		}
		if(i == s.length()){
			return true;
		}
		return false;
	}