leetcode——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 tt 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.

解析:題目比較簡單,只需要判斷是否s中每一個字符在t中都按順序存在。用兩個變量j和k分別指向s和t,k每次加1,而j只需要當t[k]=s[j]時加1,若s的每一個字母都在t中按順序出現,則返回true。算法複雜度只有O(s.length + t.length),代碼短小精悍!


class Solution {
public:
	bool isSubsequence(string s, string t) {
		int j = 0, l1 = s.length(), l2 = t.length();
		for(int k=0; k<l2&&j<l1; k++)
			if(t[k]==s[j])	j ++;
		return j==l1;
	}
};





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章