這個雖然簡單,效率也不高,但面試還是經常考的,試著寫寫看。Coding makes you exact
?1
const
?
char
*
?MyStrStr(
const
?
char
?
*
text,?
const
?
char
?
*
pattern)
?2
{
?3
????
int
?i?
=
?
0
,?j?
=
?
0
;
?4
?5
????
while
?(pattern[i]?
&&
?text[j])
?6
????
{
?7
????????
if
?(pattern[i]?
==
?text[j])
?8
????????
{
?9
????????????
++
i;
10
????????????
++
j;
11
????????}
?
12
????????
else
13
????????
{
14
????????????i?
=
?
0
;
15
????????????j?
=
?j?
-
?i?
+
?
1
;
16
????????}
17
????}
//
while
18
19
????
if
?(
!
pattern[i])
20
????
{
21
????????
return
?text?
+
?j?
-
?i;
22
????}
?
23
????
else
24
????
{
25
????????
return
?
0
;
26
????}
27
}
const
?
char
*
?MyStrStr(
const
?
char
?
*
text,?
const
?
char
?
*
pattern)?2
{?3
????
int
?i?
=
?
0
,?j?
=
?
0
;?4
?5
????
while
?(pattern[i]?
&&
?text[j])?6
????
{?7
????????
if
?(pattern[i]?
==
?text[j])?8
????????
{?9
????????????
++
i;10
????????????
++
j;11
????????}
?12
????????
else
13
????????
{14
????????????i?
=
?
0
;15
????????????j?
=
?j?
-
?i?
+
?
1
;16
????????}
17
????}
//
while
18
19
????
if
?(
!
pattern[i])20
????
{21
????????
return
?text?
+
?j?
-
?i;22
????}
?23
????
else
24
????
{25
????????
return
?
0
;26
????}
27
}
需要注意的地方是line#15, line#21。j - i 表示之前前進的步數,+1表示從下個位置比較


