Skip to content

Commit e7bb4e7

Browse files
committed
feat: add the solution of Length of Last Word(058) with kotlin.
1 parent 9888c01 commit e7bb4e7

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
| [035][035-question] | [Search Insert Position][035-tips] | [][035-java] | | [][035-kotlin] |
4141
| [038][038-question] | [Count and Say][038-tips] | [][038-java] | | [][038-kotlin] |
4242
| [053][053-question] | [Maximum Subarray][053-tips] | [][053-java] | | [][053-kotlin] |
43-
| [058][058-question] | [Length of Last Word][058-tips] | [][058-java] | | |
43+
| [058][058-question] | [Length of Last Word][058-tips] | [][058-java] | | [][058-kotlin] |
4444
| [066][066-question] | [Plus One][066-tips] | [][066-java] | | |
4545
| [067][067-question] | [Add Binary][067-tips] | [][067-java] | | |
4646
| [069][069-question] | [Sqrt(x)][069-tips] | [][069-java] | | |
@@ -477,4 +477,5 @@
477477
[035-kotlin]: ./src/_035/kotlin/Solution.kt
478478
[038-kotlin]: ./src/_038/kotlin/Solution.kt
479479
[053-kotlin]: ./src/_053/kotlin/Solution.kt
480+
[058-kotlin]: ./src/_058/kotlin/Solution.kt
480481
[771-kotlin]: ./src/_771/kotlin/Solution.kt

src/_058/kotlin/Solution.kt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package _058.kotlin
2+
3+
/**
4+
* @author relish
5+
* @since 2018/04/18
6+
*/
7+
class Solution {
8+
fun lengthOfLastWord(s: String): Int {
9+
var count = 0
10+
for (i in s.length - 1 downTo 0) {
11+
if (s[i] == ' ') {
12+
if (count == 0) continue
13+
return count
14+
} else {
15+
count++
16+
}
17+
}
18+
return count
19+
}
20+
}
21+
22+
fun main(args: Array<String>) {
23+
println(Solution().lengthOfLastWord("a "))
24+
println(Solution().lengthOfLastWord("Hello World"))
25+
}

tips/058/README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Output: 5
2222

2323
题意是让你从一个只包含大小字母和空格字符的字符串中得到最后一个单词的长度,很简单,我们倒序遍历,先得到最后一个非空格字符的索引,然后再得到它前面的空格字符索引,两者相减即可。当然,我们使用 API 来完成这件事更加方便,只需一行代码 `return s.trim().length() - s.trim().lastIndexOf(" ") - 1;`,但我相信作者出这道题的目的肯定不是考你 API 的使用,所以我们还是用自己的思路来实现。
2424

25+
java:
2526
```java
2627
class Solution {
2728
public int lengthOfLastWord(String s) {
@@ -34,6 +35,23 @@ class Solution {
3435
}
3536
```
3637

38+
kotlin(196ms/100.00%):
39+
```kotlin
40+
class Solution {
41+
fun lengthOfLastWord(s: String): Int {
42+
var count = 0
43+
for (i in s.length - 1 downTo 0) {
44+
if (s[i] == ' ') {
45+
if (count == 0) continue
46+
return count
47+
} else {
48+
count++
49+
}
50+
}
51+
return count
52+
}
53+
}
54+
```
3755

3856
## 结语
3957

0 commit comments

Comments
 (0)