# Conquering LeetCode #12

Easy question: Length of Last Word.

Given a stringsconsists of upper/lower-case alphabets and empty space characters`' '`

, return the length of last word in the string.

If the last word does not exist, return 0.

Note:A word is defined as a character sequence consists of non-space characters only.

For example,

Givens=`"Hello World"`

,

return`5`

.

This is probably the easiest problem I’ve ever solved. The only somewhat tricky part was realizing that a word could end with a space. The solution was to trim the string before doing anything with it.

public class Solution {

public int lengthOfLastWord(String s) {

int counter = 0;

s = s.trim();

for (int i = s.length() - 1; i >= 0; i--){

if (s.charAt(i) == ' '){

return counter;

}

counter++;

}

return s.length();

}

}

— -

The second problem I solved was just as easy: Plus One

Given a non-negative integer represented as anon-emptyarray of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

At first glance, its simple. Just add a 1 to the end of the array. But if the end of the array is a 9, then set that to 0 and add 1 to the second-last element, and so on.

When I submitted my solution, it failed a test case where digits was [9]. The result was supposed to be [1, 0]. I had incorrectly assumed that the head of the array would never be 9. Whoops. Shouldn’t assume things.

But anyway, creating a new array wasn’t a problem. It was even easier when I remembered that initializing an integer array in Java sets all values to be 0. So I just had to change the first value to a 1.

public class Solution {

public int[] plusOne(int[] digits) {

for (int i = digits.length - 1; i >= 0; i--){

if (digits[i] == 9){

digits[i] = 0;

} else {

digits[i] = digits[i] + 1;

return digits;

}

}

int[] toReturn = new int[digits.length + 1];

toReturn[0] = 1;

return toReturn;

}

}