【LeetCode OJ 242】Valid Anagram
2016-01-18 19:53
323 查看
题目链接: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
package com.test.demo;
/**
* @author 徐剑
* @Time 2015-01-18
*/
public class Solution
{
public boolean isAnagram(String s, String t)
{
int[] s_num=fun(s);
int[] t_num=fun(t);
for(int i=0;i<s_num.length;i++)
{
if(s_num[i]!=t_num[i])
{
return false;
}
}
return true;
}
/**
* 初始化一个长度为26的数组,初始值为0,代表a-z的个数
* @param str
* @return
*/
private int[] fun(String str)
{
int num[]=new int[26];
for(int i=0;i<str.length();i++)
{
int k = Integer.valueOf(str.charAt(i)).intValue()-97;
num[k]++;
}
return num;
}
}
题目: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
package com.test.demo;
/**
* @author 徐剑
* @Time 2015-01-18
*/
public class Solution
{
public boolean isAnagram(String s, String t)
{
int[] s_num=fun(s);
int[] t_num=fun(t);
for(int i=0;i<s_num.length;i++)
{
if(s_num[i]!=t_num[i])
{
return false;
}
}
return true;
}
/**
* 初始化一个长度为26的数组,初始值为0,代表a-z的个数
* @param str
* @return
*/
private int[] fun(String str)
{
int num[]=new int[26];
for(int i=0;i<str.length();i++)
{
int k = Integer.valueOf(str.charAt(i)).intValue()-97;
num[k]++;
}
return num;
}
}
相关文章推荐
- UVA-1663 Purifying Machine (最大匹配数)
- Android 异常解决 content.ActivityNotFoundException: Unable to find explicit activity class
- 线程池与cp命令的实现
- 搭建个人博客&论坛(LAMP):wordpress、discuz、phpMyAdmin
- Vijos P1097 合并果子(优先队列 贪心)
- 文档翻译第003篇:Process Monitor帮助文档(Part 3,附Process Monitor的简单演示)
- Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
- 2946: [Poi2000]公共串 二分+hash
- 协同过滤算法python实现简单入门详细注释
- SSH中主键生成策略
- 已解决的问题————"struct cocos2d::Color3B const cocos2d::ccRED"
- SAP FICO事务码F110替代
- curl 303
- css-div下内容垂直居中
- Django - “no module named django.core.management”
- Structure and inference in annotated networks - note
- listener-thread: err = -25572
- erlang集群IP及port管理
- Androidclient和server端数据交互的第一种方法
- pig对null的处理(实际,对空文本处理为两种取值null或‘’)