242. Valid Anagram

Source: Internet
Author: User

Given, Strings s and T, write a function to determine if it is a anagram of s. /c1>

For example,

S = "Anagram", t = "Nagaram", return true.

s = "Rat", t = "Car", return false.

Note:

assume the string contains only lowercase alphabets.

Problem Solving Ideas:

Returns true as long as the characters of S and T and the same number of characters are used. The characters used in this question are lowercase, so you can use a fixed-size array as a hash array, recording the number of occurrences of a character in a string ....

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;

}

};

Or

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;

}

};

Another way is to use map to record the number of occurrences of each character, the process is similar to ...

242. Valid Anagram

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.