判斷子序列一個字符串是否是另一個字符串的子序列
解釋:字符串的一個子序列是原始字符串刪除一些(也可以不刪除)字符,不改變剩余字符相對位置形成的新字符串。
?? ? ?如,"ace"是"abcde"的一個子序列。
?? ??? ? ?"aec"不是"abcde"的子序列。
示例 1:
?? ?輸入:s1 = "ac", s2 = "ahbgdc"
?? ?輸出:true
示例 2:
?? ?輸入:s = "ax", t = "acdgbgdc"
?? ?輸出:false
解析:
? ? ? ? ?按照s2的字符串順序去找,如果s1是s2的子序列,那么一定能找到對應的s1中的所有字符,
? ? ? ? ?如果遍歷了s2,而s1中還有剩余的長度沒有找到,那么說明s1不是s2的子序列。
示例源碼:
// Len_findChild.cpp : 此文件包含 "main" 函數。程序執行將在此處開始并結束。
//#include <iostream>
#include <string>
using namespace std;
bool JudgeChildStr(string s, string t)
{int count = s.size() - 1;for (int i = t.size() - 1; i >= 0 && count >= 0; i--){if (t[i] == s[count]){count--;}}if (count < 0){return true;}return false;
}int main()
{string s1 = "ac";string s2 = "ahbgdc";bool bResult = JudgeChildStr(s1, s2);printf("\n\ts1 = %s \n\ts2 = %s \n\tresult: %s\n", s1.c_str(), s2.c_str(), (bResult==0)?("false"):("true"));s1 = "ax";s2 = "acdgbgdc";bResult = JudgeChildStr(s1, s2);printf("\n\ts1 = %s \n\ts2 = %s \n\tresult: %s\n", s1.c_str(), s2.c_str(), (bResult == 0) ? ("false") : ("true"));}
執行結果:
?