Description:
Assume that there is A character string A consisting of letters, and the character string B contains fewer letters. In what way can I find all the letters in string B in string A as soon as possible?
For example, if it is the following two strings:
String 1: ABCDEFGHLMNOPQRS
String 2: DCGSRQPO
The answer is true, and all the letters in string2 also have string1.
For the following two strings:
String 1: ABCDEFGHLMNOPQRS
String 2: DCGSRQPZ
The answer is false because the Z letter in the second string is not in the first string.
# Include
# Include
# Include
# Include
# Include
Using namespace std; // first method: Use hash_table for // O (n + m) bool include (string & a, string & B) {hash_set
Hs; for (char t: a) hs. insert (t); for (char t: B) if (hs. find (t) = hs. end () return false; return true;} // Method 2: prime number method, learned // O (m + n) // array of prime numbers int primeNumber [26] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101}; bool include2 (string & a, string & B) {// long product = 1 must be used here; // code of the large integer division, which is given in the following header. // Traverse the long string to obtain the product of the prime number corresponding to each character for (char t: a) {int index = t-'A'; product = product * primeNumber [index];} // traverse the short string for (char t: B) {int index = t-'A'; // if the remainder is not 0, the characters in the short string are not included, if (product % primeNumber [index]! = 0) return false;} return true;} // The third method is to use a binary bit to indicate whether bool encoding DE3 (char * a, char * B) exists) {int have = 0; while (* a) {have | = 1 <(* (a ++)-'A'); // set .. Z corresponds to 0 .. 26} while (* B) {if (have & (1 <(* (B ++)-'A') = 0) {return false ;}} return true ;}int main () {// freopen ("C: \ in.txt", "r", stdin ); string a = "ABCDEFGHLMNOPQRS"; string B = "DCGSRQPO"; if (include (a, B) cout <"include \ n"; if (include (, b) cout <"contains \ n"; return 0 ;}