給定兩個字串 s1 和 s2,請撰寫一個程式,確定其中一個字串的字符重新排列后,能否變成另一個字串,
一、題目要求
- 示例一:
輸入: s1 = "abc", s2 = "bca"
輸出: true
示例二:
輸入: s1 = "abc", s2 = "bad"
輸出: false
- 說明:
0 <= len(s1) <= 100
0 <= len(s2) <= 100
二、演算法示例
先重排,再比較
- Swift
func CheckPermutation(_ s1: String, _ s2: String) -> Bool {
if s1.count != s2.count {
return false
} else if s1 == s2 {
return true
}
return s1.sorted() == s2.sorted()
}
- C
bool CheckPermutation(char* s1, char* s2){
if (s1 == NULL || s2 == NULL ||
strlen(s1) != strlen(s2)) {
return false;
}
int sum = 0;
int ans = 0;
for (int i=0; i<strlen(s1); ++i) {
ans ^= s1[i];
ans ^= s2[i];
sum += s1[i];
sum -= s2[i];
}
return ans == 0 && sum == 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/72907.html
標籤:其他
下一篇:影像處理領域頂級期刊及會議
