The algorithm---string contains

Source: Internet
Author: User
string contains Title Description

Given two string A and string B, which are composed of letters, the length of string B is shorter than string a. How can I tell you how quickly all the letters in string B are in string a?

For the sake of simplicity, we stipulate that the input string contains only uppercase English letters, implement the function bool Stringcontains (string &a, String &b)

For example, if it is the following two strings:

String 1:ABCD

String 2:bad

The answer is true, that is, the letters in the String2 are also in String1, or String2 is a true subset of STRING1.

If it is the following two strings:

String 1:ABCD

String 2:BCE

The answer is false, because the E-letter in the string String2 is not in the string String1.

Also, if String1:abcd,string 2:aa, the same returns true. Analysis and Solution

The topic description is long, but test instructions is very clear, is given a long short two string A, a, suppose a long B short, the need to determine whether B is included in the string A.

It may seem simple at first glance, but it's not easy to achieve, and if the interviewer is pressing, a way to veto what you can think of, it will be a lot of brains to give you better and best solutions. Solution One

Determine if the characters in the string2 are in string1? The most intuitive and simplest way to do this is to compare each character in the string2 with each of the characters in the string1 to see if it is in String1.

The code can be written as follows:

BOOL Stringcontain (String &a,string &b)
{for
    (int i = 0; i < b.length (); ++i) {
        int J;
        for (j = 0; (J < A.length ()) && (a[j]! = B[i]); ++J)
            ;
        if (J >= a.length ())
        {
            return false;
        }
    }
    return true;
}

Assuming that n is the length of the string String1 and M is the length of the string String2, then this algorithm requires an O (n*m) operation. Obviously, the time overhead is too great to find a better way. Solution Two

If sorting is allowed, we can consider sorting. For example, you can sort the letters of the two strings first, and then poll the two characters in turn. The ordering of two strings requires (General) O (M log m) + O (n log n) operations, followed by a linear scan that requires O (m+n) operations.

For the sorting method, you can use the most commonly used quick sort, the reference code is as follows:

Note that a B may contain repeating characters, so note that a subscript does not move easily. This method changes the string. If you do not want to change please copy
bool Stringcontain (string &a,string &b)
{
    sort (a.begin (), A.end ());
    Sort (B.begin (), B.end ());
    for (int pa = 0, PB = 0, Pb < B.length ();)
    {while
        ((PA < A.length ()) && (A[pa] < B[PB]))
        {
  ++pa;
        }
        if (PA >= a.length ()) | | (A[pa] > B[PB]))
        {
            return false;
        }
        A[PA] = = B[PB]
        ++pb;
    }
    return true;
}
Solution Three

There is no better way than a quick sort.

Let's consider this issue in a different way:

Suppose there is a string consisting only of letters, so that each letter corresponds to a prime number, starting from 2, and so on, a corresponds to 3,c corresponding to 2,b 5, .... Iterate through the first string and multiply each letter by the corresponding prime number. Will eventually get an integer.

Using the correspondence of the letters and primes above, corresponding to the letters in the second string, then polling, with each letter corresponding to the number of primes in addition to the previous integer. If the result is a number, the result is false. If there is no remainder in the process, then the second string is a subset of the first (judging if it is a true subset, you can compare two strings corresponding to the prime number product, if equality is not a true subset).

The idea is summarized as follows: According to the order from small to large, with 26 primes respectively with the character ' A ' to ' Z ' one by one corresponds. Traverse a long string to obtain the product of the corresponding prime number for each character. Traverse short strings to determine whether the product is divisible by the prime number of characters in the short string. Output results.

As mentioned earlier, the algorithm's time Complexity O (m+n) is the best case O (n) (traverse the first number of short strings, and the multiplication of long string primes, that is, the remainder, you can exit the program, return false), n is the length of long strings, space complexity is O (1).

This method has only theoretical significance because the integer product is large and has an overflow risk of
bool Stringcontain (string &a,string &b)
{
    const int p[26] = {2, 3, 5, 7, 1 1,,,,,,,,,,,,,,,,,,,,,,, 59,61,,,,,,,,,,,,, 101};
    int f = 1;
    for (int i = 0; i < a.length (); ++i)
    {
        int x = p[a[i]-' a '];
        if (f% x)
        {
            f *= x;
        }
    }
    for (int i = 0; i < b.length (); ++i)
    {
        int x = p[b[i]-' A '];
        if (f% x)
        {
            return false;
        }
    }
    return true;
}

This method of multiplying the primes seems perfect, but the disadvantage is that the multiplication of prime numbers can easily lead to integer overflows. Solution Four

If the interviewer keeps asking, is there a better way? Count sort. In addition to the counting sort.

In fact, it is possible to put all the characters in a long string A into a hashtable, and then poll the short string B to see if each character of the short string B is in Hashtable, and if it exists, the long string A contains the short string B, otherwise, the description is not included.

Further, we can calculate a "signature" for string A, a bitwise operation (26bit integer representation), and then use the character in B to find it in a.

"Best method", Time complexity O (n + m), Spatial complexity O (1)
bool Stringcontain (string &a,string &b)
{
    int hash = 0;
    for (int i = 0; i < a.length (); ++i)
    {
        hash |= (1 << (A[i]-' a '));
    }
    for (int i = 0; i < b.length (); ++i)
    {
        if (hash & (1 << (b[i]-' A ')) = = 0)
        {
            return fals e;
        }
    }
    return true;
}

The essence of this method is to replace the Hashtable with an integer, with a spatial complexity of O (1) and a time complexity of O (n + m). Extrapolate

1, conjugation if the character of two strings, but the order is different, is considered to be a sibling string, such as bad and ADB is the brother string, now provides a string, how to quickly find its brother string in the dictionary, describe the data structure and query process.

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.