File tree Expand file tree Collapse file tree 3 files changed +76
-0
lines changed
Expand file tree Collapse file tree 3 files changed +76
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string } s
3+ * @return {number }
4+ */
5+ var lengthOfLastWord = function ( s ) {
6+ let stack = [ ] ;
7+ const newS = s . trim ( )
8+ for ( let i = 0 ; i < newS . length ; i ++ ) {
9+ const val = newS [ i ]
10+ if ( val === ' ' ) {
11+ stack = [ ]
12+ } else {
13+ stack . push ( val )
14+ }
15+ }
16+ return stack . length
17+
18+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string[] } strs
3+ * @return {string }
4+ */
5+ var longestCommonPrefix = function ( strs ) {
6+ let prefix = strs [ 0 ]
7+ for ( let i = 1 ; i < strs . length ; i ++ ) {
8+ while ( strs [ i ] . indexOf ( prefix ) !== 0 ) {
9+ prefix = prefix . substring ( 0 , prefix . length - 1 )
10+ }
11+ }
12+ return prefix
13+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string[] } strs
3+ * @return {string }
4+ */
5+ var longestCommonPrefix = function ( strs ) {
6+ if ( ! strs || strs . length === 0 ) return "" ;
7+ if ( strs . length === 1 ) return strs [ 0 ] ;
8+
9+ class TrieNode {
10+ constructor ( ) {
11+ this . children = new Map ( ) ;
12+ this . isEnd = false ;
13+ this . passCount = 0 ;
14+ }
15+ }
16+
17+ const root = new TrieNode ( ) ;
18+
19+ for ( const word of strs ) {
20+ let node = root ;
21+ for ( const ch of word ) {
22+ if ( ! node . children . has ( ch ) ) {
23+ node . children . set ( ch , new TrieNode ( ) ) ;
24+ }
25+ node = node . children . get ( ch ) ;
26+ node . passCount += 1 ;
27+ }
28+ node . isEnd = true ;
29+ }
30+
31+ let node = root ;
32+ let prefix = "" ;
33+
34+ while ( node . children . size === 1 ) {
35+ const [ [ ch , next ] ] = node . children . entries ( ) ;
36+
37+ if ( next . passCount !== strs . length ) break ;
38+
39+ prefix += ch ;
40+ node = next ;
41+ if ( node . isEnd ) break ;
42+ }
43+
44+ return prefix ;
45+ } ;
You can’t perform that action at this time.
0 commit comments