今天的三道题目都特别简单,直接上题目和解法~~
58.,Length of Last Word题目:
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.
Example:
Input: "Hello World"
Output: 5
就是找到最后一个单词的长度,和昨天题目一样,trim去除空格:
//59%
public int lengthOfLastWord(String s) {
return s.trim().length()-s.trim().lastIndexOf(" ")-1;
}
//59%
public int lengthOfLastWord1(String s){
int count = -1, i = s.length();
while (--i >= 0 && s.charAt(i) == ' ');
while (i - ++count >= 0 && s.charAt(i - count) != ' ');
return count;
}
67.,Add Binary题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
二进制加法:
//46%
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() -1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) sum += b.charAt(j--) - '0';
if (i >= 0) sum += a.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
383, Ransom Note题目:
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
判断一个字符串是否可以从另一个字符串完全构造,直接对每个字符计数即可,代码如下所示,其中第二种方法可以实现早停,所以代码的效率比较高:
//45%
public boolean canConstruct(String ransomNote, String magazine) {
if(ransomNote.length() > magazine.length())
return false;
int [] count = new int [26];
for(int i=0; i<magazine.length(); i++){
if(i<ransomNote.length())
count[ransomNote.charAt(i)-'a'] ++;
count[magazine.charAt(i)-'a'] --;
}
for(int num : count)
if(num > 0)
return false;
return true;
}
//87%
public boolean canConstruct2(String ransomNote, String magazine) {
int[] table = new int[26];
for (char c : magazine.toCharArray()) table[c - 'a']++;
for (char c : ransomNote.toCharArray())
if (--table[c - 'a'] < 0) return false;
return true;
}