按char字符串的顺序检查chars子集

时间:2015-04-22 20:36:27

标签: algorithm

所有

我想检查一下string1是否按顺序包含string2中的所有字符,我想知道我该怎么做?

For example:

string1 = "abcdeda"
string2 = "ba"

it will return true because by removing first a and cded you can left ba which matches.

谢谢

2 个答案:

答案 0 :(得分:1)

index = -1
str1 = "abcdeda"
str2 = "ba"

for c in str2
    tmp = indexOf(c , str1 , index)
    if tmp != -1
        index = tmp
    else
        return //no match at c

indexOf(c , str , index): first index of c in str after index, or -1,  i
                          if no occurence was found   

答案 1 :(得分:0)

尝试:

String string1 = "abcdeda"
String string2 = "ba"

Bool isFound;

for(int i = 0; i < string2.length; i++ ) {
    isFound = false;
    for(int y = 0; y < string1.length; y++ ) {
        if(string2[i] == string1[y]) {
            isFound = true;
        }
    }
    if(!isFound) {
        return false;
    } 
}

return true;