473,587 Members | 2,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Big O and algorithm to decide string A contains string B?

I need to implement a function to return True/false whether String A
contains String B. For example, String A = "This is a test"; String B =
"is is". So it will return TRUE if String A includes two "i" and two
"s". The function should also handle if String A and B have huge
values, like two big dictionary.

What's the best approach to achieve this with the best performance?
what's the Big O then?

I am thinking to put A and B into two hashtable, like key = "i" and
value = "2" and so on. Then compare these two hashtable. But how to
compare two hashtables? Please advise.

Jul 18 '05 #1
13 8731
us***@yahoo.com wrote:
I need to implement a function to return True/false whether String A
contains String B. For example, String A = "This is a test"; String B =
"is is". So it will return TRUE if String A includes two "i" and two
"s". The function should also handle if String A and B have huge
values, like two big dictionary.

What's the best approach to achieve this with the best performance?
what's the Big O then?

I am thinking to put A and B into two hashtable, like key = "i" and
value = "2" and so on. Then compare these two hashtable. But how to
compare two hashtables? Please advise.


One simple possibility is to iterate through each position i within
string A and see if the substring A(i,i+length(B) ) = B. Java and C++
have facilities to make this quite simple. The worst case runtime is
O(length(A)*len gth(B)) under reasonable assumptions about how string
comparisons are performed.

Perhaps one can do better if one is clever.
Jul 18 '05 #2
<us***@yahoo.co m> wrote in message
I need to implement a function to return True/false whether String A
contains String B. For example, String A = "This is a test"; String B =
"is is". So it will return TRUE if String A includes two "i" and two
"s". The function should also handle if String A and B have huge
values, like two big dictionary.
Because String B = "is is" (note the space), should the function return true
if String A contains two "i", two "s", one space?

The first step would be to parse String B so that we know to expect 2 "i", 2
"s", 1 " ".

What's the number of distinct chars? Is it A-Z and a-z for a total of 52?
If the number of distinct chars is small, say 256 distinct chars, create an
array, such as unsigned expect[256], to represent the number of chars to
expect. expect['i'] would equal 2, expect['s'] would equal 2, expect[' ']
would equal 1, and all other expect elements would be zero. If the number
of distinct chars is large, then you could use a map<char_type, unsigned> or
hashtable.

Now step through every char in String A. Let the char in question be char
c. Decrement expect[c] by one, but if it is zero then don't decrement it.
Now check if all the elements in expect are zero. As an optimization, you
only need to do this check if you decremented expect[c].

To check if all the elements in expect are zero, you could for example
create another array zero, such as unsigned zero[256] = {0}, and use memcmp
to compare expect to zero. There are other ways, maybe platform specific
ways that might be faster.

Remember to deal with the special case that String B is the empty string, in
which case you can probably immediately return true.
What's the best approach to achieve this with the best performance?
what's the Big O then?
My algorithm is O(length(String A)) + O(length(String B)).
I am thinking to put A and B into two hashtable, like key = "i" and
value = "2" and so on. Then compare these two hashtable. But how to
compare two hashtables? Please advise.


In principle it is doable, but putting all the chars of String A into a
hashtable might be rather expensive.

To compare two hashtables, you could iterate through the elements in the
first hash table, using a for_each(hash1. begin(), hash1.end()) structure, or
even for (Iter iter = hash1.begin(); iter != hash1.end(); ++iter). For each
element in hash1, look up the corresponding value in hash2, for example
hash2[iter->key]. Then check if the values are equal, for example
iter->value == hash2[iter->key].
Jul 18 '05 #3
I do not quite undertstand the problem. You write that the function
should return true when string A contains string B. But your example
shows that it should return true when string A contains all characters
that are in string B. This is something very different. Which one is
your problem?

cheers,
Marcin Kalicinski

Jul 18 '05 #4

<us***@yahoo.co m> schrieb im Newsbeitrag
news:11******** *************@o 13g2000cwo.goog legroups.com...
I need to implement a function to return True/false whether String A
contains String B. For example, String A = "This is a test"; String
B =
"is is". So it will return TRUE if String A includes two "i" and two
"s". The function should also handle if String A and B have huge
values, like two big dictionary.

What's the best approach to achieve this with the best performance?
what's the Big O then?

I am thinking to put A and B into two hashtable, like key = "i" and
value = "2" and so on. Then compare these two hashtable. But how to
compare two hashtables? Please advise.


bool XY(const char* src, const char* seek)
{
std::map<char, int> counter;
std::map<char, int>::iterator it;

// Fill map with number of chars in dest
for(; *seek!='\0'; ++seek)
{
if(is_char_to_b e_counted(*seek ))
++counter[*seek];
}
// subtract the count of these chars on src
for(; *src!='\0'; ++src)
{
it = counter.find(*s rc);
if(it!=counter. end() && --it->second<0)
return false; // src has more 'x's than dest
}
// See if any of these has different count
for(it=counter. begin(); it!=counter.end (); ++it)
{
if(it->second) return false; // dest has more 'x's than src
}
return true;
}

this should so the trick quickly. If you really have chars, you can
replace the std::map with a simple array of 256 ints...
-Gernot
Jul 18 '05 #5
Acutally the problem is not about String Matching. The function will
return TRUE if string A contains all characters
that are in string B. Or String A has what String B has. For example,
String B is "issi" and String A is "This is a test", the function will
return TRUE. So what if String A and B have big values, what's the best
algorithm and Big O to achieve this?

I am thinking creating two hashtable. For String B, key=i, value=2;
key=s, value=2. For String A, key=i, value=2; key=s, value=3, etc. Then
compare this two hashtable. So constructing these two hashtable will be
expensive but the Big O will be O(nlogn). Is it good?

Jul 18 '05 #6
us***@yahoo.com wrote:
) Acutally the problem is not about String Matching. The function will
) return TRUE if string A contains all characters
) that are in string B. Or String A has what String B has. For example,
) String B is "issi" and String A is "This is a test", the function will
) return TRUE. So what if String A and B have big values, what's the best
) algorithm and Big O to achieve this?
)
) I am thinking creating two hashtable. For String B, key=i, value=2;
) key=s, value=2. For String A, key=i, value=2; key=s, value=3, etc. Then
) compare this two hashtable. So constructing these two hashtable will be
) expensive but the Big O will be O(nlogn). Is it good?

Why a hashtable ? There are only 256 different characters, so you
can just make an array with 256 entries and count.

The BigO will be O(n).
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
Jul 18 '05 #7
Yes. An array with 256 entries should be enough. But how to create an
array using char as the index? array index is supposed to be int,
right? For example, array[0] = 'a' instead of array['a'] = 0. Sorry, I
am a newbie to algorithm...

Jul 18 '05 #8
us***@yahoo.com wrote:

Yes. An array with 256 entries should be enough. But how to create an
array using char as the index? array index is supposed to be int,
right?
a char is nothing more then a small integer in C and C++. Only
during input and output a char is treated differently.
For example, array[0] = 'a' instead of array['a'] = 0. Sorry, I
am a newbie to algorithm...


array['a'] = 0;

is fine. (Remember: a char is nothing more then an small integer. Its
value is the code number of the character on your system).

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 18 '05 #9

us***@yahoo.com wrote:
Yes. An array with 256 entries should be enough. But how to create an
array using char as the index? array index is supposed to be int,
right? For example, array[0] = 'a' instead of array['a'] = 0. Sorry, I am a newbie to algorithm...


char is an integral type, like short, int and long. They'll convert
without problems. i.e.

int frequency[ 1<<CHAR_BIT ] = {0}; // typically 256 entries
std::string A = foo();
for( int i=0;i!=A.size() ; ++i )
++frequency[ A[i] ];

std::string B = bar();
for( int i=0;i!=B.size() ; ++i )
if( frequency[ B[i] ]-- == 0 )
std::cout << "B not in A";

Obvious O(A.size+B.size ) and you can't do better
in general.

HTH,
Michiel Salters

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
12966
by: jose luis fernandez diaz | last post by:
Hi, Does any know a algorithm to strip heading and leading blank in a string ? Tnansk, Jose Luis
4
7100
by: Ben Fidge | last post by:
Hi What is the most efficient way to gather a list of files under a given folder recursively with the ability to specify exclusion file masks? For example, say I wanted to get a list of all files under \Program Files and it's subdirectories that meet the following criteria:
2
30497
by: GRB | last post by:
A client wants me to decrypt a cookie. They encrypted the data in java using TripleDES. The key provided is a 168 bit 44 character key, DESede alogorithm. Ive tried to decrypt in vb.net and get the above error. Below is the class I use and the code I use to call it. Not sure wher I'm going wrong here. The TripleDES service provider only uses a 192 bit 24 character length key. Any help would be greatly appreciated.
6
25356
by: aarklon | last post by:
Hi folks, I found an algorithm for calculating the day of the week here:- http://www.faqs.org/faqs/calendars/faq/part1/index.html in the section titled 2.5 what day of the week was 2 august 1953 I checked the algorithm it is very correct.
2
7278
by: Julio C. Hernandez Castro | last post by:
Dear all, We have just developped a new block cipher called Raiden, following a Feistel Network structure by means of genetic programming. Our intention now consists on getting as much feedback as possible from users, so we encourage you to test the algorithm and send us your opinion. We would also like to receive enhancements and new versions of the algorithm, developed in other source languages and platforms. Our idea on developing...
1
2595
by: hn.ft.pris | last post by:
"Forward maximum match" mean that there is a dictionary contains thousands of items which are single words. For example, "kid", "nice", "best"... And here get a string "kidnicebs", the forward maximum match algorithm need to find the longest string that matches the string in dictionary. Because the longest string in the dictionary has a length of 4, so the algoritm pick the first four characters of the string(that's why it's called...
4
32058
prometheuzz
by: prometheuzz | last post by:
Hello (Java) enthusiasts, In this article I’d like to tell you a little bit about graphs and how you can search a graph using the BFS (breadth first search) algorithm. I’ll address, and hopefully answer, the following questions: • what is a graph? • how can a graph be represented as an ADT? • how can we search/walk through a graph using the BFS algorithm?
20
3060
by: mike3 | last post by:
Hi. (Xposted to both comp.lang.c++ and comp.programming since I've got questions related to both C++ language and general programming) I've got the following C++ code. The first routine runs in like 65% of the time of the second routine. Yet both do the same thing. However, the second one seems better in terms of the way the code is written since it helps encapsulate the transformation in the inner loop better making it easier to read,...
2
3803
by: slizorn | last post by:
hi guys, i need to make a tree traversal algorithm that would help me search the tree.. basically i need to read in a text file... shown below H H,E,L E,B,F B,A,C A,null,null c,null,D
0
8219
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8349
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7978
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8221
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6629
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5395
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3845
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.