diff --git a/58.length-of-last-word.java b/58.length-of-last-word.java new file mode 100644 index 0000000..e410fdc --- /dev/null +++ b/58.length-of-last-word.java @@ -0,0 +1,30 @@ +/* + * @lc app=leetcode id=58 lang=java + * + * [58] Length of Last Word + */ + +// @lc code=start +class Solution { + public int lengthOfLastWord(String s) { + if(s == null || s.isBlank()) { + return 0; + } + int i = s.length() - 1; + while(i >= 0 && s.charAt(i) == ' ') { + i--; + } + int r = 0; + while(i >= 0) { + if(s.charAt(i) != ' ') { + r++; + i--; + } else { + break; + } + } + return r; + } +} +// @lc code=end +