leetcode.com/problems/length-of-last-word/
Length of Last Word - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
1. Problem
Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.
A word is a maximal substring consisting of non-space characters only
2. Code
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "Hello Wo rld";
String s2 = " ";
String s3 = "b a ";
int result = lengthOfLastWord(s3);
System.out.println(result);
}
public static int lengthOfLastWord(String s) {
while(s.length() > 0 && s.charAt(s.length()-1) == ' ') {
s = s.substring(0, s.length()-1);
}
int lastBlank = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' ') {
lastBlank = i + 1;
}
}
return s.length() - lastBlank;
}
3. Report
문자열을 반복해서 substring으로 처리하여 속도가 늦었다.
'algorithm' 카테고리의 다른 글
[leetCode] 57. Insert Interval (0) | 2021.01.18 |
---|---|
[LeetCode] 28. Implement strStr() (0) | 2021.01.17 |
[LeetCode] 9. Palindrome Number (0) | 2021.01.07 |
[LeetCode] 7. ReverseInteger (0) | 2021.01.07 |
[LeetCode] 2. Add Two Numbers (0) | 2020.12.26 |