Let contain the alphabet, and let contain the string that Farmer John heard. We'll process the characters of string sequentially, finding each current character in the alphabet . We move through the alphabet from left to right, starting a new pass from its beginning whenever the required letter appears to the left of the previous letter.
Example
In this example, the cowphabet is ordered the same way as the regular alphabet. Bessie must mumble the cowphabet at least times. Below, the way Bessie mumbled is shown, with uppercase letters indicating the letters that Farmer John heard.
Algorithm implementation
Read the alphabet and the string .
cin >> alph;
cin >> s;Keep track of the number of passes through the alphabet using the variable .
cnt = 0;Use the variable to iterate through the characters of the string sequentially.
for (i = 0; i < s.size(); )
{Use the variable to iterate through the letters of the alphabet. As soon as we find the next required letter in the alphabet, increment by .
for (j = 0; j < alph.size(); j++)
if (s[i] == alph[j]) i++;
cnt++;
}Print the answer.
cout << cnt << endl;