### 只出现一次的数字

class Solution {
public:
int singleNumber(vector<int>& v) {
int x = 0;
for (auto &&i : v) {
x ^= i;
}
return x;
}
};



### 859. 亲密字符串

class Solution {
public:
bool buddyStrings(string s, string goal) {
if (s.size() != goal.size() || s.size() <= 1) {
return false;
}
vector<int> delta(s.size());
char c[2];
int diff = 0;
int sum = 0;
for (int i = 0; i < s.size(); i++) {
delta[i] = s[i] - goal[i];
sum += s[i] - goal[i];
if (delta[i] != 0) {
diff++;
c[i % 2] = s[i];
}
}
if (sum != 0) {
cout << "sum != 0" << endl;
return false;
}
if (diff == 1 || diff > 2) {
cout << "diff == 1 || diff > 2" << endl;
return false;
}
if (c[0] != c[1]) {
cout << "c[0] != c[1]" << endl;
return false;
}

print_vec(delta);
return true;
}
};


class Solution {
public:
bool buddyStrings(string s, string goal) {
int cnt = 0;
if (s.size() != goal.size()) return false;

int diff1 = -1; // 第一次不同的位置
int diff2 = -1; // 第二次不同的位置
int chars[26];
memset(chars, 0, sizeof(chars));
bool valid_no_diff = false;

for (int i = 0; i < s.size(); i++) {
if (s[i] != goal[i]) {
cnt++;
if (cnt > 2) return false;
if (cnt == 1) diff1 = i;
if (cnt == 2) diff2 = i;
}
chars[s[i]-'a']++;
if (chars[s[i] - 'a'] >= 2) valid_no_diff = true;
}

if (cnt == 0 && valid_no_diff) return true; // 两个串一摸一样，需要有两个以上相同字母出现
if (cnt == 2 && s [diff1] == goal [diff2] && s [diff2] == goal [diff1]) return true; // 两个串有两个位置不同，需要正好可以互换

return false;
}
};


### 20. 有效的括号

class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for (int i = 0; i < s.size(); i++) {
switch (s[i]) {
case '(':
case '{':
case '[':
stk.push(s[i]);
break;
default:
if(stk.empty()) return false;
auto top = stk.top();
auto exp = top == '('
? ')'
: (top == '[' ? ']' : (top == '{' ? '}' : '\0'));
if (s[i] != exp) {
printf("%c got %c\n", exp, s[i]);
return false;
}
stk.pop();
break;
}
}
if(!stk.empty()) return false;
return true;
}
};