当前位置:网站首页>Morphemes

Morphemes

2021-01-23 22:06:14 Ding does not cook

* The problem of morphemes
 * Deformed words , That is, two strings with the same number of characters .
 * problem : Given two strings , Programming , After determining one of the strings and rearranging the characters , Can it become another character .
 * return bool, Represents whether two strings can be the same after rearrangement .
 * Ideas :
 * Method 1: Convert a string to an array of characters , Then sort the array of characters , utilize Arrays Of equal Function to judge whether it is equal .
 * Method 2: Open up new auxiliary space , namely 256 Integer array , Do counting use .
 * Scan string 1, Convert the character that appears in it to ASCII value , On the corresponding auxiliary array +1;
 * Scan string 2, Convert the character that appears in it to ASCII value , On the corresponding auxiliary array -1;
 *      If it's negative after subtraction , Go straight back to false;
 * Scan auxiliary array , Greater than 0 The value of appears , Go straight back to false

 

 1 private static boolean checkSame1(String str1, String str2) {
 2         int len1=str1.length();
 3         int len2=str1.length();
 4         if(len1!=len2)
 5             return false;
 6         char []arr1=str1.toCharArray();
 7         char []arr2=str2.toCharArray();
 8         Arrays.sort(arr1);
 9         Arrays.sort(arr2);
10         
11         
12         return Arrays.equals(arr1, arr2);
13     }
Method 1

 

 1 private static boolean checkSame2(String str1, String str2) {
 2         int len1=str1.length();
 3         int len2=str1.length();
 4         if(len1!=len2)
 5             return false;
 6         
 7         int []helper=new int [256];
 8         // String 1 To the auxiliary array ;
 9         for (int i = 0; i < len1; i++) {
10             char c=str1.charAt(i);
11             helper[c]++;
12         }
13         // String 2 Elements in helper Subtract the corresponding position of 
14         for (int i = 0; i < len2; i++) {
15             char c=str2.charAt(i);
16             helper[c]--;
17             if(helper[c]<0)
18                 return false;
19         }
20         for (int i = 0; i < helper.length; i++) {
21             if(helper[i]>0)
22                 return false;
23             return true;
24 }
25         return true;
26     }
Method 2

 

1     public static void main(String[] args) {
2         String str1 = "aa bcde fagq";
3         String str2 = "aa bdce fagy";
4         boolean res=checkSame2(str1, str2);
5         System.out.println(res);
6         
7     }
The main function

版权声明
本文为[Ding does not cook]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/01/20210123220511125E.html

随机推荐