给定一个字符串 s 和一些 长度相同 的单词 words 。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符 ,但不需要考虑 words 中单词串联的顺序。
这道题的思路就是先取一个相同长度的字符串与words数组中字符串进行比较,相同i的位置就加上字符串的长度减一,在最开始的时候保存i的最开始的位置,便于下次从i的加一位置开始遍历。不相同的就就从i+1的位置开始遍历。
源码:
public List < Integer > findSubstring ( String s, String [ ] words) {
int len= words[ 0 ] . length ( ) ;
int index= 0 ;
int count= 0 ;
int [ ] matching= new int [ 1000 ] ;
int mn= 0 ;
boolean state= false ;
List < String > list= new ArrayList < > ( ) ;
for ( int i= 0 ; i< words. length; i++ ) {
list. add ( words[ i] ) ;
}
int z= 0 ;
for ( int i= 0 ; i<= s. length ( ) - len; i++ ) {
if ( count== 0 ) {
if ( state) {
z++ ;
i= z;
list= new ArrayList < > ( ) ;
for ( int x= 0 ; x< words. length; x++ ) {
list. add ( words[ x] ) ;
}
state= false ;
}
index= i;
}
for ( int k= 0 ; k< list. size ( ) ; k++ ) {
if ( ! list. get ( k) . equals ( s. substring ( i, i+ len) ) ) {
if ( k== list. size ( ) - 1 ) {
count= 0 ;
i= z;
state= true ;
}
}
else if ( list. get ( k) . equals ( s. substring ( i, i+ len) ) ) {
count++ ;
i+= len- 1 ;
if ( count== words. length) {
matching[ mn] = index;
i= z;
mn++ ;
count= 0 ;
state= true ;
}
list. remove ( k) ;
break ;
}
}
}
List < Integer > list1= new ArrayList < > ( ) ;
for ( int i= 0 ; i< mn; i++ ) {
list1. add ( matching[ i] ) ;
}
return list1;
}