Skip to content

Commit 7500608

Browse files
committed
Add Length of Last Word C#
1 parent 6cafde2 commit 7500608

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Solutions in various programming languages are provided. Enjoy it.
2121
12. [Combination Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/12-Combination-Sum-III)
2222
13. [Insert Interval](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/13-Insert-Interval)
2323
14. [House Robber](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/14-House-Robber)
24+
15. [Length of Last Word](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/15-Length-of-Last-Word)
2425

2526
## August LeetCoding Challenge
2627
Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions.
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
public class Solution {
2+
3+
//Solution 1
4+
public class Solution {
5+
public int LengthOfLastWord(string s) {
6+
if(s.Length == 0) return 0;
7+
8+
var l = s.Split(' ').ToList();
9+
var i = l.Count - 1;
10+
while(i >= 0){
11+
if(l[i] == ""){
12+
i--;
13+
}
14+
else{
15+
return l[i].Length;
16+
}
17+
}
18+
19+
return 0;
20+
}
21+
}
22+
23+
24+
//Solution 2
25+
public int LengthOfLastWord(string s)
26+
{
27+
if (s.Length == 0) return 0;
28+
29+
int beginPosition = 0;
30+
int endPosition = 0;
31+
bool hasWord = false;
32+
bool hasSpaceBeforeLastWord = false;
33+
34+
//Start by the end of string
35+
for (int i = s.Length - 1; i >= 0; i--)
36+
{
37+
if (s[i] == ' ' && !hasWord)
38+
{
39+
//This condition improves performance
40+
continue;
41+
}
42+
else if (s[i] != ' ' && !hasWord)
43+
{
44+
hasWord = true;
45+
endPosition = i;
46+
continue;
47+
}
48+
else if (s[i] == ' ' && hasWord)
49+
{
50+
beginPosition = i;
51+
hasSpaceBeforeLastWord = true;
52+
break;
53+
}
54+
}
55+
56+
//One word case
57+
if (endPosition - beginPosition == 0 && hasWord)
58+
return 1;
59+
60+
//No words case
61+
if (endPosition - beginPosition == 0 && !hasWord)
62+
return 0;
63+
64+
//Has word and has spaces before last words
65+
if (endPosition - beginPosition != 0 && hasWord && hasSpaceBeforeLastWord)
66+
return endPosition - beginPosition;
67+
68+
//Has word and has no space before last words
69+
if (endPosition - beginPosition != 0 && hasWord && !hasSpaceBeforeLastWord)
70+
return endPosition - beginPosition + 1;
71+
72+
return 0;
73+
}
74+
}

0 commit comments

Comments
 (0)