[Leetcode]242.valid Anagram

Source: Internet
Author: User

Topic

Given, strings s and t, write a function to determine if it is a anagram of S.

Example 1:

Input:s = "Anagram", T = "Nagaram"
Output:true
Example 2:

Input:s = "Rat", t = "Car"
Output:false

Note:
Assume the string contains only lowercase alphabets.

Solution Ideas

The question means: whether the string s and T are composed of the same characters: for example, there are 2 a in S, 4 b,t if the same, it is called S and T is anagram.
If s and t have inconsistent lengths, the direct return is false.
Because the title assumes that all letters are lowercase, we use an int array of length 26, with each element to save the number of characters in S and T. If present in S, then--if present in ++;t, then--; In this case, if s and T are exactly the same, then each element in the array should be 0.

Code
class Solution {    public boolean isAnagram(String s, String t) {        if(s.length() != t.length()) return false;        int[] count = new int[32];        for(int i = 0; i < s.length(); i++) {            count[s.charAt(i) - ‘a‘]++;            count[t.charAt(i) - ‘a‘]--;        }                for(int i:count)            if(i != 0) return false;                return true;    }}

[Leetcode]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.