GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode-1/algorithms/cpp/buddyStrings/BuddyStrings.cpp at master · mtangm/leetcode-1 Expand file tree/ Copy pathBuddyStrings.cppMore file actions 94 lines (85 loc) · 1.72 KB / Copy pathBuddyStrings.cppFile metadata and controls94 lines (85 loc) · 1.72 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 // Source : https://leetcode.com/problems/buddy-strings/description/ // Author : Hao Chen // Date : 2018-06-27 /*************************************************************************************** * * Given two strings A and B of lowercase letters, return true if and only if we can * swap two letters in A so that the result equals B. * * * * Example 1: * * * * Input: A = "ab", B = "ba" * Output: true * * * * Example 2: * * * Input: A = "ab", B = "ab" * Output: false * * * * Example 3: * * * Input: A = "aa", B = "aa" * Output: true * * * * Example 4: * * * Input: A = "aaaaaaabc", B = "aaaaaaacb" * Output: true * * * * Example 5: * * * Input: A = "", B = "aa" * Output: false * * * * * Note: * * * 0 <= A.length <= 20000 * 0 <= B.length <= 20000 * A and B consist only of lowercase letters. * * * * * ***************************************************************************************/ class Solution { public: bool buddyStrings(string A, string B) { if (A.size() != B.size()) return false; if (A.size()<2) return false; bool bRepeat = false; bool map[26] = {false}; int idx[2], diffCnt=0; for (int i=0; i<A.size(); i++){ if (map[A[i]-'a']) { bRepeat = true;} map[A[i]-'a']=true; if ( A[i] != B[i] ) { if (diffCnt>=2) return false; idx[diffCnt++] = i; } } //if A == B and there has repeated chars , then return true if (diffCnt==0 && bRepeat) return true; return (A[idx[0]] == B[idx[1]] && A[idx[1]] == B[idx[0]]); } }; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |