当前位置:网站首页>[leetcode] 7. valid anagram · effective letter ectopic words
[leetcode] 7. valid anagram · effective letter ectopic words
2022-07-28 12:03:00 【AQin1012】
Title Description
Description in English
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
English address
https://leetcode.com/problems/valid-anagram/
Description of Chinese version
Given two strings s and t , Write a function to determine t Whether it is s Letter heteronym of . Be careful : if s and t Each character in the has the same number of occurrences , said s and t They are mutually alphabetic words .
Example 1: Input : s = "anagram", t = "nagaram" Output : true Example 2: Input : s = "rat", t = "car" Output : false
Advanced : If the input string contains unicode What about characters ? Can you adjust your solution to deal with this situation ?
Constraints · Tips :
1 <= s.length, t.length <= 5 * 104
s and t Only lowercase letters
Address of Chinese version
https://leetcode.cn/problems/valid-anagram/
Their thinking
Use Map The structure stores the letters read and the number of occurrences , namely Map< character , Number of occurrences >
Specific steps :
First compare the length of two strings , Inequality returns directly false
Same degree , At the same time through , From a string s Add the characters read in map( If none, add directly , If there is one, it should key Times of value +1), From a string t Characters read in move out map( If nothing, add , The number of occurrences is -1, If there is one, it should key Times of value -1)
The number of times of traversal judgment removal is 0 Of key value
Judge map Is it empty : Empty return true; Instead, return to false
How to solve the problem
My version

class Solution {
public boolean isAnagram(String s, String t) {
Map<Character, Integer> map = new HashMap<>();
StringBuffer stringBuffer1 = new StringBuffer(s);
int length1 = s.length();
StringBuffer stringBuffer2 = new StringBuffer(t);
int length2 = t.length();
if (length1 != length2) {
return false;
}
int len = length1;
for (int i = 0; i < len; i++) {
char cc = stringBuffer1.charAt(i);
char tc = stringBuffer2.charAt(i);
if (map.containsKey(cc)) {
map.put(cc, map.get(cc) + 1);
} else {
map.put(cc, 1);
}
if (map.containsKey(tc)) {
map.put(tc, map.get(tc) - 1);
} else {
map.put(tc, -1);
}
if (map.get(cc) != null) {
if (map.get(cc) == 0) {
map.remove(cc);
}
}
if (map.get(tc) != null) {
if (map.get(tc) == 0) {
map.remove(tc);
}
}
}
if (map.isEmpty()) {
return true;
}
return false;
}
}Official edition
Method 1 : Sort

class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char[] str1 = s.toCharArray();
char[] str2 = t.toCharArray();
Arrays.sort(str1);
Arrays.sort(str2);
return Arrays.equals(str1, str2);
}
}Complexity analysis
- Time complexity :O(nlogn)
- Spatial complexity :O(logn)
Method 2 : Hashtable

class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] table = new int[26];
for (int i = 0; i < s.length(); i++) {
table[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
table[t.charAt(i) - 'a']--;
if (table[t.charAt(i) - 'a'] < 0) {
return false;
}
}
return true;
}
}
Advanced questions

class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> table = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) + 1);
}
for (int i = 0; i < t.length(); i++) {
char ch = t.charAt(i);
table.put(ch, table.getOrDefault(ch, 0) - 1);
if (table.get(ch) < 0) {
return false;
}
}
return true;
}
}Complexity analysis
- Time complexity :O(n), among n by s The length of
- Spatial complexity :O(s), among s Is the character set size , here s=26
High praise version

class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length())
return false;
int[] alpha = new int[26];
for(int i = 0; i< s.length(); i++) {
alpha[s.charAt(i) - 'a'] ++;
alpha[t.charAt(i) - 'a'] --;
}
for(int i=0;i<26;i++)
if(alpha[i] != 0)
return false;
return true;
}
}summary
The high praise answer is to use a set to store the order of characters , Plus... Appears in a string , If it appears in another string, it will decrease , The last occurrence times are 0 Then it proves that the two strings are exactly the same , But it is very clever that Gao Zan's reply is cleverly used 26 The order of letters and characters ASCII Code value , Only one size is used 26 Of int Arrays are cleverly stored 26 The order in which characters appear ( Unlike my clumsy use of key value pairs ), But if we consider the advanced problem , Using key value pairs still has advantages .
边栏推荐
- R language uses dplyr package group_ By function and summarize function calculate the mean value of all covariates involved in the analysis based on grouped variables (difference in means of covariate
- 15、用户web层服务(三)
- Database advanced learning notes - system package
- Design and implementation of SSM personal blog system
- Specific process of strong cache and negotiation cache
- Hcip (configuration of GRE and mGRE and OSPF related knowledge)
- R language ggplot2 visualization: use the ggdotplot function of ggpubr package to visualize the grouped dot plot, set the palette parameter, and set the color of data points in different grouped dot p
- async await如何实现并发
- Network communication protocol classification and IP address
- Alexnet - paper analysis and reproduction
猜你喜欢

直接插入排序与希尔排序

强缓存、协商缓存具体过程

瑞吉外卖——Day01

LabVIEW AI visual Toolkit (non Ni vision) download and installation tutorial

Consumer installation and configuration

Service Workers让网站动态加载Webp图片

Redis installation

Service workers let the website dynamically load webp pictures

14、用户web层服务(二)

A new mode of one-stop fixed asset management
随机推荐
Can dynamic partitions be configured when MySQL is offline synchronized to ODPs
Interfaces and abstract classes
瑞吉外卖——Day01
Client service registration of Nacos registry
async await如何实现并发
Consumer installation and configuration
Unity 一键替换场景中的物体
Some knowledge concepts
Modify the running container port mapping
Service workers let the website dynamically load webp pictures
学会使用MySQL的Explain执行计划,SQL性能调优从此不再困难
Solutions to slow start of MATLAB
Matlab sets the size of graphics window and image and the position of legend
游戏流程与底层实现 逐步完成
Skiasharp's WPF self drawn drag ball (case version)
Traversal and copy of files in jar package
Lua makes a deep copy of table
The game process and the underlying implementation are gradually completed
The reflect mechanism obtains the attribute and method information of class
Test platform (V) knowledge points supplement