Skip to content

Instantly share code, notes, and snippets.

@Jeffwan
Last active August 29, 2015 13:56
Show Gist options
  • Save Jeffwan/8856782 to your computer and use it in GitHub Desktop.
Save Jeffwan/8856782 to your computer and use it in GitHub Desktop.
Length of Last Word on LeetCode
package leetcode.stringSimple;
/**
* Method 1: General way, remeber to check if count =0 when meet " "
* Do I need to change first condition to (str[i]!= ' ') ? I think it doesn't matter.
*
*
* Method 2: " ".isEmpty() " ".length() == false!!! If we use this way, we must include s.trim().isEmpty() at first.
* Or, it will splited as String[] arr, the length of arr equals to 0, so there will be a ArrayOutofBound Exception.
*
* Test case: " " , "Hello World "
*
*/
public class LengthOfLastWord {
// test case: Str may end up with '' -- most important part
public static void main(String args[]) {
System.out.println(lengthOfLastWord2(" "));
}
public static int lengthOfLastWord(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] str = s.toCharArray();
int count = 0;
for (int i = str.length - 1; i >= 0; i--) {
if ((str[i] >= 'a' && str[i] <='z') || (str[i] >= 'A' && str[i] <= 'Z')) {
count++;
}
if (str[i] == ' ') {
if (count == 0) {
continue;
} else {
// have already go through a word
return count;
}
}
}
return count;
}
private static int lengthOfLastWord2(String s) {
// if s = " ", s.isEmpty == false because there's a blank!
if (s == null || s.length() == 0 || s.trim().isEmpty()) {
return 0;
}
String[] arr = s.split(" ");
return arr[arr.length - 1].length();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment