File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
3+
4+ 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
5+
6+ 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
7+
8+ 示例 1:
9+ s = "abc", t = "ahbgdc"
10+ 返回 true.
11+ */
12+
13+ // var isSubsequence = function(s, t) {
14+ // var lastIndex = -1
15+ // var sliced = t
16+ // var slicedCount = 0
17+ // for (var i = 0; i < s.length; i++) {
18+ // var finded = sliced.indexOf(s[i])
19+ // if (finded + slicedCount > lastIndex) {
20+ // lastIndex = finded + slicedCount
21+ // sliced = sliced.substr(finded + 1)
22+ // slicedCount += finded + 1
23+ // continue
24+ // }else {
25+ // return false
26+ // }
27+ // }
28+ // return true
29+ // }
30+
31+ // 这种是速度最快的 利用indexOf的第二个参数做起点
32+ var isSubsequence = function ( s , t ) {
33+ let start = 0
34+ for ( let i = 0 ; i < s . length ; i ++ ) {
35+ let index = t . indexOf ( s [ i ] , start )
36+ if ( index === - 1 ) return false
37+ start = index + 1
38+ }
39+ return true
40+ } ;
41+
42+ var a = "leeeeetcode"
43+ var b = 'leeeeeeeeeeccccctcccoddddeeee'
44+ console . log ( isSubsequence ( a , b ) )
You can’t perform that action at this time.
0 commit comments