程序员面试经典
题目要求
给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串中的空格。
给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。
核心思想
方法1.先排序,后一一对比。
方法2.用ASCII码值进行对比
完整代码如下(从牛客经典的Github链接上抄下来的一篇优秀代码,自己写的有点low)
public class question_3 {
//方法1.先排序,后对比。
public static String sort(String s) {
char[] content = s.toCharArray();
java.util.Arrays.sort(content);
return new String(content);
}
public static boolean permutation(String s, String t) {
return sort(s).equals(sort(t));
}
//方法2.
public static boolean anagram(String s, String t) {
if (s.length() != t.length())
return false;
int[] letters = new int[128];
//建立128个元素的数组,int的默认值为0
int num_unique_chars = 0;
int num_completed_t = 0;
char[] s_array = s.toCharArray();
for (char c : s_array) { // count number of each char in s.
if (letters[c] == 0)
++num_unique_chars;//如果这个ASCII第一次出现,则加到num_unique_chars里.
++letters[c];//找到对应ASCII码值,数量加1,即当前ASCII码值的数的数量加1;
}
for (int i = 0; i < t.length(); ++i) {
int c = (int) t.charAt(i);
if (letters[c] == 0) { // Found more of char c in t than in s.即如果当前B数组里有的字符的ASICC值在数组A没有出现过,那么就确定B中有A中没有的字符;
return false;
}
--letters[c];//当前元素数量减1
if (letters[c] == 0) {
++num_completed_t;//B的所有字符数
if (num_completed_t == num_unique_chars) {
// itÕs a match if t has been processed completely B的所有字符和A的所有字符;
return true;
//return i == t.length() - 1;
}
}
}
return false;
}
public static void main(String[] args) {
String[][] pairs = {{"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}};
for (String[] pair : pairs) {
String word1 = pair[0];
String word2 = pair[1];
boolean anagram = permutation(word1, word2);
System.out.println(word1 + ", " + word2 + ": " + anagram);
System.out.println(anagram(word1, word2));
}
}
}
补充
8中基本数据类型的默认值:
①byte short int long 这四种基本数据类型数组默认值为0
②float double 这两种数组默认值是0.0
③char这种类型数组默认值为空格
④boolean类型数组默认值为false