forked from Jensenczx/CodeEveryday
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3_LengthOfLastWord.java
More file actions
35 lines (33 loc) · 867 Bytes
/
3_LengthOfLastWord.java
File metadata and controls
35 lines (33 loc) · 867 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
/**
* @param s A string
* @return the length of last word
*/
public static int lengthOfLastWord(String s) {
// Write your code here
if(s==null||s.length()==0)
return 0;
int length = 0;
boolean flag = false;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) != ' '){
if(flag == true){
flag = false;
length = 0;
}
length++;
}
else flag = true;
}
return length;
}
public static int lengthOfLastWord(String s){
if(s == null || s.length() == 0)
return 0;
String [] array = s.split(' ');
return array[array.length-1];
}
public static void main(String []args){
System.out.println(lengthOfLastWord("Hello World "));
}
}