28. 找出字符串中第一个匹配项的下标
方法一
class Solution {
public :
int strStr ( string haystack, string needle) {
if ( haystack. find ( needle) == string:: npos) {
return - 1 ;
}
return haystack. find ( needle) ;
}
} ;
方法二
class Solution {
public :
int strStr ( string haystack, string needle) {
int haystackLength = haystack. length ( ) ;
int needleLength = needle. length ( ) ;
int haystackIndex = 0 , needleIndex = 0 ;
while ( haystackIndex < haystackLength) {
if ( haystack[ haystackIndex] != needle[ needleIndex] ) {
haystackIndex = haystackIndex - needleIndex;
needleIndex = 0 ;
}
else {
if ( needleIndex == needleLength- 1 ) {
return haystackIndex- needleLength+ 1 ;
}
needleIndex++ ;
}
haystackIndex++ ;
}
return - 1 ;
}
} ;
class Solution {
public :
int strStr ( string haystack, string needle) {
int haystackLength = haystack. size ( ) , needleLength = needle. size ( ) ;
if ( needleLength == 0 ) {
return 0 ;
}
vector< int > next ( needleLength) ;
for ( int i= 1 , j= 0 ; i< needleLength; i++ ) {
while ( j> 0 && needle[ i] != needle[ j] ) {
j = next[ j- 1 ] ;
}
if ( needle[ i] == needle[ j] ) {
j++ ;
} ;
next[ i] = j;
}
for ( int i= 0 , j= 0 ; i< haystackLength; i++ ) {
while ( j> 0 && haystack[ i] != needle[ j] ) {
j = next[ j- 1 ] ;
}
if ( haystack[ i] == needle[ j] ) {
j++ ;
}
if ( j== needleLength) {
return i - needleLength + 1 ;
}
}
return - 1 ;
}
} ;