C# 求字符串中是否包含另一字符串的排列
例如,字符串1"abcdefg"就包含有字符串2"cb",因为字符串1中有"bc"子字符串,经过排列后可为"cb"。
View Code
static bool IsPermutation(string str1, string str2) { if (String.IsNullOrEmpty(str1)||String.IsNullOrEmpty(str2)) { throw new Exception("input can't be empty"); } Hashtable ht = new Hashtable(); Hashtable ht2 = new Hashtable(); for (int i = 0; i < str1.Length; i++) { if (ht[str1[i]]==null) { ht[str1[i]] = 1; } else { ht[str1[i]] = Int32.Parse(ht[str1[i]].ToString()) + 1; } } for (int i = 0; i < str2.Length; i++) { if (ht2[str2[i]] == null) { ht2[str2[i]] = 1; } else { ht2[str2[i]] = Int32.Parse(ht2[str2[i]].ToString()) + 1; } } for (int i = 0; i < str2.Length; i++) { if (!ht[str2[i]].Equals(ht2[str2[i]])) { return false; } } return true; }