Sie sind auf Seite 1von 17

What is string?

Rules to define a string:


1. If a symbol a then a is a string.
2. If x and y are two string then xy is a
string.
3. Nothing else is a string.
Eg:if ={a,b,c} then
abc,abbca




IsEmpty(string s)
stringLength(string s)
String stringconcatenate(string s1, string s2)
Stringcopy(string s1,string s2)
Int stringcompare(string s1,string s2)
Int stringsearch(string s1,string s2)
Void stringsubstitute(string s1,string s2)
Array representation:


Typedef struct string
{
Int length;
Char str[1000];
}string;
H E L L O \0
Linked List Representation:


Typedef struct string
{
Char symbol;
Struct string *next;
}string;
H O \0 L L E
Brute force Algorithm
Knuth morris pratt Algorithm
Rabin Karp Algorithm
check for a match between the first characters of the pattern
with the first character of the string . If they dont match we
move forward the second character of the string.

int brutestringsearch(char *s,char *p)
{
int i,j,k,m,n;
n=strlen(s);
m=strlen(p);
for(i=0;i<=(n-m);i++)
{
j=0;
k=I;
while((s[k]==p[j])&&(j<m))
{
K++;
}
if(j==m)
return I;
}
return(-1)
}
Complexity is o(mn).
It can be very useful
Doesnt require pre-processing of the text
Doesnt require additional space
Can be quite effective for short texts and
patterns
It can be ineffective
If we search more than once the text
Its slow

searches for occurrences of a pattern" P within a main "text
string" S by employing the observation that when a mismatch
occurs, the word itself embodies sufficient information to
determine where the next match could begin.
Eg:
P = "ABCDABD" and S = "ABC ABCDAB ABCDABCDABDE

Iteration 1:
m=0,i=0

M:01234567890123456789012
S:ABC ABCDAB ABCDABCDABDE
P: ABCDABD
i: 0123456
Iteration 2:
m = 4 and i = 0.
m: 01234567890123456789012
S: ABC ABCDAB ABCDABCDABDE
P: ABCDABD
i: 0123456
Iteration 3:
m = 8, i = 2.
m: 01234567890123456789012
S: ABC ABCDAB ABCDABCDABDE
P: ABCDABD
i: 0123456
Iteration 4:
m = 11, i = 0.

m: 01234567890123456789012
S: ABC ABCDAB ABCDABCDABDE
p: ABCDABD
i: 0123456
Iteration 5:
m = 15, i = 0.

m: 01234567890123456789012
S: ABC ABCDAB ABCDABCDABDE
p: ABCDABD
i: 0123456

int KMP(char *s,char *p)
{
int i,j,m,n;
n=strlen(s);
m=strlen(p);
for(i=0,j=0;i<n && j<m;i++,j++)
while((j>=0)&& (s[i]!=p[j]))
j=next[j];
if(j==m)
return i-m;
else
return -1;
}
Eg;
Let S=ababbaababababb
P=abababb
i=0123456
Next
[i]
-1 0 0 1 2 3 5
i 0 1 2 3 4 5 6
Void getnext(char *p,int next[])
{
int i,j;
int m=strlen(p);
next[0]=-1;
for(j=1;j<m;j++)
{
i=next[j-1];
while((i>=0)&&(p[j-1]!=p[i]))
i=next[i];
next[j]=i+1;
}


Time complexity for precomputing a table is
o(n).
Best case:o(k)
Worstcase:o(kn)

Das könnte Ihnen auch gefallen