【LeetCode算法-58/66】Length of Last Word/Plus One

LeetCode第58題:git

Given a string s consists 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.spa

Example:翻譯

Input: "Hello World" Output: 5

翻譯:code

獲取最後一個單詞的長度blog

思路:element

思路很簡單,要注意一點就是一些特殊狀況,好比全是空格、或者只有一個單詞string

代碼:it

class Solution { public int lengthOfLastWord(String s) { s = s.trim(); if(s.length() == 0 ){ return 0; } if(s.length() == 1){ return 1; } return s.length() - 1 -s.lastIndexOf(" "); } }

 

LeetCode第66題:

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

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

Example 1:

Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.

翻譯:

說了一大推,其實就是數組最後一個數字加1,可是數組的每一個數字必須是個位數

思路:

其實就是整數的加法邏輯,如今改爲數組,把其中的邏輯寫出來而已。必須注意的是9加1等於10,要進一位

代碼:

class Solution { public int[] plusOne(int[] digits) { int length = digits.length; digits[length - 1] += 1; for(int i = length -1 ;i>=0;i--){ if(digits[i] == 10){ digits[i] = 0; if(i!=0){ digits[i - 1] +=1; }else{
            //新建一個數組
int[] result = new int[length+1]; result[0] = 1; for(int j = 1;j<result.length;j++){ result[j] = digits[j-1]; } return result; } } } return digits; } }

歡迎關注個人微信公衆號:安卓圈

相關文章
相關標籤/搜索