题目
- Total Accepted: 27326
- Total Submissions: 61741
- Difficulty: Medium
- Contributor: LeetCode
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.
思路
题目需要判断字符串s是否是字符串t的子串。其中子串的定义是通过删除某些字符但不改变所有字符排列顺序的情况下能得到的字符串。
思路是对字符串s的每一个字符,依次在字符串t中进行查找,同时每次查找的开始位置是上一次查找的结束位置,以保证顺序性。
源程序
class Solution {
public:
bool isSubsequence(string s, string t) {
int l1 = s.size(),l2 = t.size();
int i,j;
j = 0;
for(i = 0;i < l1;i ++){
while(t[j] != s[i] && j < l2)
j ++;
if(j == l2)
break;
j ++;
}
if(i == l1)
return true;
else
return false;
}
};
本文介绍了一个经典的编程问题:如何判断一个字符串是否为另一个字符串的子序列。子序列是指通过删除某些字符但保持其余字符相对顺序不变所形成的字符串。文章详细阐述了解决此问题的思路与实现方法。
4780

被折叠的 条评论
为什么被折叠?



