讲一下题意,题目不要理解错了,给定一个字符串s,给定一个vectorwords里面包含单词,题目所说的那句’all of the same length’请忽略(完全不懂什么意思。。)目的是找出s中是否存在vector中单词连接而成的字符子串,返回出现的地址
解法:设map标记vector中words的出现次数,遍历s,每找到一个对应的words,map标记–,清空(string)temp
void initializeMap ( map< string, int > & m, vector< string> words) {
for ( int i = 0 ; i < words. size ( ) ; ++ i) {
if ( m. count ( words[ i] ) == 0 ) m[ words[ i] ] = 1 ;
else m[ words[ i] ] + = 1 ;
}
}
vector< int > findSubstring ( string s, vector< string> & words) {
vector< int > res;
if ( ! words. size ( ) ) return res;
int words_Length = 0 ;
int words_max = 0 ;
for ( int i = 0 ; i < words. size ( ) ; ++ i) {
words_Length + = words[ i] . length ( ) ;
if ( words[ i] . length ( ) > words_max) words_max = words[ i] . length ( ) ;
}
for ( int i = 0 ; i < s. size ( ) ; ++ i) {
map< string, int > m;
initializeMap ( m, words) ;
if ( i + words_Length > s. size ( ) ) break ;
string temp;
for ( int j = i; j <= i + words_Length; ++ j) {
temp + = s[ j] ;
if ( temp. size ( ) > words_max) break ;
if ( m. count ( temp) ) {
if ( m[ temp] ) {
m[ temp] - = 1 ;
temp = "" ;
}
}
}
bool flag = true ;
for ( map< string, int > :: iterator j = m. begin ( ) ; j != m. end ( ) ; ++ j) {
if ( j- > second >= 1 ) {
flag = false ;
break ;
}
}
if ( flag) res. push_back ( i) ;
}
return res;
}
```