171. Excel Sheet Column Number
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28
思路:不是很懂为什么这道题这么简单,然后AC率还这么低。。。。。。。。。
public class Solution {
public int titleToNumber(String s) {
int n = 0;
for(int i=0;i<s.length();i++){
n=n*26+s.charAt(i)-'A'+1;
}
return n;
}
}
122. Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
思路:其实我没有特别懂为什么这样就是对的。但是我又不可否认它是对的。。
public class Solution {
public int maxProfit(int[] prices) {
if ( prices.length < 2 ) return 0;
int max = 0;
for(int i=0;i<prices.length-1;i++){
if(prices[i+1]>prices[i])
max+=prices[i+1]-prices[i];
}
return max;
}
}
242. Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
public class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()) return false;
int[] sa= new int[26];
int[] st = new int[26];
for(int i=0;i<s.length();i++){
sa[s.charAt(i)-'a']++;
st[t.charAt(i)-'a']++;
}
for(int i=0;i<26;i++){
if(sa[i]!=st[i])
return false;
}
return true;
}
}
这道题官方给的做法
#1 把两个字符串sort(按照字母排序),排序后的字符串应该是一模一样的。但是这个算法复杂度为O(n log n),我感觉不是很好啊。但是优点在于,空间复杂度是O(1)~
#2 是我的算法的改进版本,嗯!
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] counter = new int[26];
for (int i = 0; i < s.length(); i++) {
counter[s.charAt(i) - 'a']++;
counter[t.charAt(i) - 'a']--;
}
for (int count : counter) {
if (count != 0) {
return false;
}
}
return true;
}
好像落了一题TOP K Frequent Element,明天做。。
原来Arrays.sort()的时间复杂度是O(nlogn)啊……