Skip to content

Commit 5c226cc

Browse files
committed
solve problem Length Of Last Word
1 parent c6383a2 commit 5c226cc

File tree

5 files changed

+63
-0
lines changed

5 files changed

+63
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ All solutions will be accepted!
154154
|234|[Palindrome Linked List](https://leetcode-cn.com/problems/palindrome-linked-list/description/)|[java/py/js](./algorithms/PalindromeLinkedList)|Easy|
155155
|414|[Third Maximum Number](https://leetcode-cn.com/problems/third-maximum-number/description/)|[java/py/js](./algorithms/ThirdMaximumNumber)|Easy|
156156
|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|
157158

158159
# Database
159160
|#|Title|Solution|Difficulty|

algorithms/LengthOfLastWord/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Length Of Last Word
2+
This problem is easy to solve
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
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+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
};
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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

0 commit comments

Comments
 (0)