Algorithm title: There are two strings made up of different letters, one long and one short, long for a short for b. Design an algorithm that returns true if all characters appearing in B appear in a, otherwise false.
The following string:
String A:ABDDFDIOEGDDDFFSFAGJ
String B:DOFSJADG
Each character in string B appears in A and returns true.
The following string:
String a:aaaabbbbbbdddddd
String B:ACC
The character in string B does not appear in a and returns false.
Answer 1: Each letter in string B is iterated through in a. This answer sucks, its time complexity is O (n*m)
Answer 2: Set up a hash table, a character traversal of string A, and set the value in the hash table corresponding to each character to 1. The characters in B are then traversed, and if all characters correspond to a hash value of 1, true is returned, otherwise false is returned.
The time complexity of the answer is O (m+n), which should be the answer most interviewers want, and most people can think of.
intStrinclude (Const Char*longone,Const Char*Shortone) { intI, allchar[ the] = {0 }; intLonglen =strlen (Longone); intShortlen =strlen (Shortone); for(i =0; i < Longlen; i++) Allchar[longone[i]]=1; for(i =0; i < Shortlen; i++) if(Allchar[shortone[i]]! =1) Break; returni = = Shortlen?1:0; }
Algorithm: whether the characters in a short string are all contained in a long string