242. Valid Anagram
来源:互联网 发布:浩方对战平台for mac 编辑:程序博客网 时间:2024/05/03 21:20
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 thestring contains only lowercase alphabets.
解题思路:
只要s和t的字符以及字符所使用的次数相同即返回true。这题中使用的字符都是小写字符,因此可直接使用固定大小的数组作为hash数组,记录字符串中字符出现的次数。。。。
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; }}; 或者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; }};
还有另一种方法就是使用map记录每个字符出现的次数,过程与上类似。。。
0 0
- [leetcode] 242.Valid Anagram
- 242.Valid Anagram
- leetcode 242. Valid Anagram
- 242. Valid Anagram
- [leetcode] 242. Valid Anagram
- leetCode 242. Valid Anagram
- Leetcode 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram LeetCode
- 242. Valid Anagram
- LeetCode 242. Valid Anagram
- LeetCode 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram
- 242. Valid Anagram
- LA 3263(p260)----That Nice Euler Circuits
- Android Studio sdk tools文件夹下文件缺失问题以及解决方法
- 238. Product of Array Except Self
- 网络基础知识(一):网络分层、UDP协议
- hdoj Jam's balance 5616 (母函数&暴力)
- 242. Valid Anagram
- UVa 699 The Falling Leaves 树的深度优先搜索
- HTML5+CSS3设计界面
- 九度题目1432
- 广师Android群分享之各版本特性
- Android Studio 使用小技巧和快捷键
- nftw,ftw
- poj 2385 Apple Catching(动态规划)
- 自定义布局之宽高比布局的实现