1. 程式人生 > >【程式設計師面試經典】確定兩串亂序同構。

【程式設計師面試經典】確定兩串亂序同構。

程式設計師面試經典

題目要求

給定兩個字串,請編寫程式,確定其中一個字串的字元重新排列後,能否變成另一個字串。這裡規定大小寫為不同字元,且考慮字串中的空格。

給定一個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