首页 > 其他 > 详细

【LeetCode OJ 242】Valid Anagram

时间:2016-01-19 10:43:19      阅读:187      评论:0      收藏:0      [点我收藏+]

题目链接: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
 技术分享技术分享
  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. }  

【LeetCode OJ 242】Valid Anagram

原文:http://blog.csdn.net/xujian_2014/article/details/50538784

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!