# (Easy) 859. Buddy Strings ## Run Code ![](https://i.imgur.com/IYoGMmx.png) ## 題意 能否對調兩個字串中的兩個字母,使得兩個字串相等。 ## 解題思路 只要找到兩個字串中不一樣的字母,對調後確認兩者是否相同。 ## 困難之處 沒看好題目,沒注意到是"兩個"字母對調,我眼殘QAQ ## Code ```cpp= class Solution { public: bool buddyStrings(string s, string goal) { //only two letters can change and they will be the same if(s.size()!=goal.size()) return false; if(s==goal && set<char>(s.begin(),s.end()).size() == s.length()) return false; // the position s and goal have different letter int dif1 = 0; int dif2 = s.size()-1; //when s[dif1]!=goal[dif1] will break for(;dif1<s.size() && s[dif1]==goal[dif1];dif1++); for(;dif2>=0 && s[dif2]==goal[dif2];dif2--); if(dif1 < dif2) swap(s[dif1],s[dif2]); return s==goal; } }; ``` ###### tags: `leetcode`