星期日, 二月 28, 2016

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.

 

 

解题思路:

只要st的字符以及字符所使用的次数相同即返回true。这题中使用的字符都是小写字符,因此可直接使用固定大小的数组作为hash数组,记录字符串中字符出现的次数。。。。

class Solution {

public:

    // 12ms

    bool isAnagram(string s, string t) {

        int n=s.length();

        if(n!=t.length())return false;

        if(n==0)return true;

        int a[26]={0};

        for(int i=0;i<n;i++){

            a[s[i]-'a']++;

            a[t[i]-'a']--;

        }

        for(int i=0;i<26;i++)

            if(a[i]!=0)return false;

        return true;

    }

};

 

或者

class Solution {

public:

    // 12ms

    bool isAnagram(string s, string t) {

        int n=s.length();

        if(n!=t.length())return false;

        if(n==0)return true;

        int a[26]={0};

        for(int i=0;i<n;i++){

            a[s[i]-'a']++;

        }

        for(int i=0;i<n;i++)

            if(a[t[i]-'a']==0)return false;

            else

                a[t[i]-'a']--;

        return true;

    }

};

 

还有另一种方法就是使用map记录每个字符出现的次数,过程与上类似。。。

238. Product of Array Except Self

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

 

解题思路:

不使用除法,返回一个数组,数组中第i个元素的值为nums[1]*..nums[i-1]*nums[i+1]…nums[n-1]

利用前n个元素的乘积数组和后n个数组的乘积数组,得到结果。

暂时是能达到60ms

class Solution {

public:

    vector<int> productExceptSelf(vector<int>& nums) {

        int n=nums.size();

        vector<int>a=vector<int>(n,0);

        a[0]=1;

        for(int i=1;i<n;i++){

            a[i]=a[i-1]*nums[i-1];

        }

        for(int i=n-1;i>0;i--){

            a[i-1]=a[i-1]*nums[i];

            nums[i-1]=nums[i]*nums[i-1];

        }

        //for(int i=0;i<n;i++)cout<<a[i]<<" ";

        return a;

    }

};