【LeetCode OJ 242】Valid Anagram

来源:互联网 发布:php防止sql注入代码 编辑:程序博客网 时间:2024/04/24 19:31

题目链接:https://leetcode.com/problems/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.

解题思路:分别统计s和t的每个字母的个数,如果均相同则为Anagram。

示例代码:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.test.demo;  
  2. /** 
  3.  * @author 徐剑 
  4.  * @Time 2015-01-18 
  5.  */  
  6. public class Solution  
  7. {  
  8.      public boolean isAnagram(String s, String t)   
  9.      {  
  10.          int[] s_num=fun(s);  
  11.          int[] t_num=fun(t);  
  12.          for(int i=0;i<s_num.length;i++)  
  13.          {  
  14.              if(s_num[i]!=t_num[i])  
  15.              {  
  16.                  return false;  
  17.              }  
  18.          }  
  19.          return true;  
  20.      }  
  21.      /** 
  22.       * 初始化一个长度为26的数组,初始值为0,代表a-z的个数 
  23.       * @param str 
  24.       * @return 
  25.       */  
  26.      private int[] fun(String str)  
  27.      {  
  28.          int num[]=new int[26];  
  29.          for(int i=0;i<str.length();i++)  
  30.          {  
  31.              int k = Integer.valueOf(str.charAt(i)).intValue()-97;  
  32.              num[k]++;  
  33.          }  
  34.          return num;  
  35.      }  
  36. }  
0 0