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;
	}
};





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