• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

2小时前 2次浏览

# leetcode每日一题-859:亲密字符串

## 代码

C++

``````class Solution {
public:

unordered_map<char, int> m;

bool buddyStrings(string s, string goal) {
if(s.size() != goal.size()) return false;
int idx1 = -1, idx2 = -1;

for(int i=0 ; i<s.size() ; i++)
{
if(s[i] == goal[i])
m[s[i]] += 1;
}

for(int i=0 ; i<s.size() ; i++)
{
if(s[i] != goal[i])
{
idx1 = i;
break;
}
}

for(int i=s.size()-1 ; i>=0 ; i--)
{
if(s[i] != goal[i])
{
idx2 = i;
break;
}
}

if(idx1 != idx2 and idx1 != -1 and idx2 != -1)
{
swap(s[idx1], s[idx2]);
return s == goal;
}

if(idx1 == idx2 and idx2 != -1) return false;

for(auto ve : m)
{
if(ve.second > 1) return true;
}

return false;
}
};
``````

Java

``````class Solution {
public boolean buddyStrings(String s, String goal) {
if (s.length() != goal.length()) {
return false;
}

if (s.equals(goal)) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
if (count[s.charAt(i) - 'a'] > 1) {
return true;
}
}
return false;
} else {
int first = -1, second = -1;
for (int i = 0; i < goal.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
if (first == -1)
first = i;
else if (second == -1)
second = i;
else
return false;
}
}

return (second != -1 && s.charAt(first) == goal.charAt(second) &&
s.charAt(second) == goal.charAt(first));
}
}
}

``````