File tree 5 files changed +63
-0
lines changed
algorithms/LengthOfLastWord
5 files changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -154,6 +154,7 @@ All solutions will be accepted!
154
154
| 234| [ Palindrome Linked List] ( https://leetcode-cn.com/problems/palindrome-linked-list/description/ ) | [ java/py/js] ( ./algorithms/PalindromeLinkedList ) | Easy|
155
155
| 414| [ Third Maximum Number] ( https://leetcode-cn.com/problems/third-maximum-number/description/ ) | [ java/py/js] ( ./algorithms/ThirdMaximumNumber ) | Easy|
156
156
| 645| [ Set Mismatch] ( https://leetcode-cn.com/problems/set-mismatch/description/ ) | [ java/py/js] ( ./algorithms/SetMismatch ) | Easy|
157
+ | 58| [ Length Of Last Word] ( https://leetcode-cn.com/problems/length-of-last-word/description/ ) | [ java/py/js] ( ./algorithms/LengthOfLastWord ) | Easy|
157
158
158
159
# Database
159
160
| #| Title| Solution| Difficulty|
Original file line number Diff line number Diff line change
1
+ # Length Of Last Word
2
+ This problem is easy to solve
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int lengthOfLastWord (String s ) {
3
+ int length = 0 ,
4
+ prevLength = 0 ;
5
+
6
+ for (char c : s .toCharArray ()) {
7
+ if (c == ' ' ) {
8
+ if (length != 0 ) {
9
+ prevLength = length ;
10
+ }
11
+ length = 0 ;
12
+ } else {
13
+ length ++;
14
+ }
15
+ }
16
+
17
+ return length == 0 ? prevLength : length ;
18
+ }
19
+ }
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 length = 0 ,
7
+ prevLength = 0 ,
8
+ prevCharacter = null
9
+
10
+ s . split ( '' ) . forEach ( c => {
11
+ if ( c === ' ' ) {
12
+ if ( length !== 0 ) {
13
+ prevLength = length
14
+ }
15
+ length = 0
16
+ } else if ( prevCharacter !== null || prevCharacter !== ' ' ) {
17
+ length += 1
18
+ }
19
+ prevCharacter = c
20
+ } )
21
+
22
+ return length === 0 ? prevLength : length
23
+ } ;
Original file line number Diff line number Diff line change
1
+ class Solution (object ):
2
+ def lengthOfLastWord (self , s ):
3
+ """
4
+ :type s: str
5
+ :rtype: int
6
+ """
7
+ length = 0
8
+ prev_length = 0
9
+
10
+ for c in s :
11
+ if c == ' ' :
12
+ if length != 0 :
13
+ prev_length = length
14
+ length = 0
15
+ else :
16
+ length += 1
17
+
18
+ return length if length != 0 else prev_length
You can’t perform that action at this time.
0 commit comments