Algorithm: whether the characters in a short string are all contained in a long string

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.