LeetCode #6
What I’ve Learned
First, We can append length of array by digits = new int[digits.length + 1];
Disclaimer
My LeetCode is free plan. I am posting just the free algorithms for now on. Also, I am using JAVA to code.
58. Length of Last Word
My Solution
In Java, there is a method that splits with the given character. When we use list.split()
, it returns with list form. It’s simple but, there are faster way I think.
class Solution {
public int lengthOfLastWord(String s) {
String[] list = s.split(" ");
return list[list.length - 1].length();
}
}
Solution
This solution is faster. It uses pointer to check if it’s whitespace or not.
class Solution {
public int lengthOfLastWord(String s) {
int count =0;
int idx = s.length()-1;
for(int i = s.length()-1; i>=0; i--) {
idx = i;
if(!Character.isWhitespace(s.charAt(i))) {
break;
}
}
for(int i = idx; i >= 0; i--) {
if(Character.isWhitespace(s.charAt(i))) {
break;
}
count++;
}
return count;
}
}
66. Plus One
My Solution
I thought there is no way to append another value in list. So, I’ve thought of using ArrayList
. It worked, but problem was with appending another. In case of 99, you need to append 1.
class Solution {
public int[] plusOne(int[] digits) {
digits[digits.length -1] += 1;
ArrayList<Integer> arr = new ArrayList<>();
for(int i = 0; i < digits.length; i++) {
arr.add(digits[i]);
}
for(int i = digits.length -1; i>0; i--) {
if(arr.get(i) == 10) {
arr.set(i, 0);
arr.set(i-1, arr.get(i-1) + 1);
}
}
System.out.print(arr);
return digits;
}
}
Solution
It’s simple, fast. Using for loop, adding 1 to increase the amount. Approach was similar but, I wasn’t smart enough to use this algorithm
class Solution {
public int[] plusOne(int[] digits) {
for(int i = digits.length -1; i>=0; i--){
if(digits[i] < 9){
digits[i]++;
return digits;
}
digits[i] = 0;
}
digits = new int[digits.length + 1];
digits[0] = 1;
return digits;
}
}