[2016/06/27] LeetCode / Java - Day 05 -

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?

思路:为每个字符串建立一个容量为26的数组,出现一个字母就对应加个数。反正是anagram的话,每个字母出现的频率应该是一样的~

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)啊……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值