当前位置:   article > 正文

针对string读取错误的方法(+anagram题解)_string识别错误

string识别错误
Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “act” and “tac” are anagram of each other.

Input:
The first line of input contains an integer T denoting the number of test cases. Each test case consist of two strings in 'lowercase' only, in a single line.

Output:
Print "YES" without quotes if the two strings are anagram else print "NO".

Constraints:
1 ≤ T ≤ 300
1|s|106

Example:
Input:
2
geeksforgeeks forgeeksgeeks
allergy allergic

Output:
YES
NO

Explanation:
Testcase 1: Both the string have same characters with same frequency. So, both are anagrams.
Testcase 2: Characters in both the strings are not same, so they are not anagrams.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
/*package whatever //do not write package name here */

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int t = Integer.parseInt(br.readLine()); //2
		while(t-->0) {
			String str = br.readLine();  //读取一行字符串 geeksforgeeks forgeeksgeeks
			String s1 = str.split(" ")[0];  //返回空格分隔的1th string:geeksforgeeks
			String s2 = str.split(" ")[1];  //返回空格分隔的2nd string:forgeeksgeeks
			char[] str1 = s1.toCharArray(); //转换为char数组
			char[] str2 = s2.toCharArray();  //转换为char数组
			
			if(anagram(str1,str2)) {
				System.out.println("YES");
			} else {
				System.out.println("NO");
			}
		}

	}
		private static boolean anagram(char[] str1, char[] str2) {
		// TODO Auto-generated method stub
		int n1 = str1.length;
		int n2 = str2.length;
		
		if(n1 != n2) return false;
		
		Arrays.sort(str1);
		Arrays.sort(str2);
		
		for(int i = 0; i < n1; i++) {
			if(str1[i] != str2[i]) return false;
		}
		return true;
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/74977?site
推荐阅读
相关标签
  

闽ICP备14008679号