fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <unordered_map>
  4. using namespace std;
  5.  
  6. string isOneAway(string s1, string s2) {
  7. if (s1.length() <= 0 || s2.length() <= 0) {
  8. return "False";
  9. }
  10. int len = 0, edits = 0;
  11. if (s1.length() > s2.length())
  12. len = s1.length() - s2.length();
  13. else
  14. len = s2.length() - s1.length();
  15.  
  16.  
  17. if (len > 1)
  18. return "False";
  19.  
  20. int i;
  21. unordered_map<char, int> s1_map;
  22. for (i =0; i < s1.length(); i++ )
  23. s1_map[s1[i]] += 1;
  24.  
  25. for (i = 0; i < s2.length(); i++) {
  26. s1_map[s2[i]] -= 1;
  27. }
  28.  
  29. for(const pair <char,int> tup: s1_map) {
  30. if (edits > 1)
  31. return "False";
  32. if (tup.second > 0)
  33. edits += 1;
  34. }
  35.  
  36.  
  37. return "True";
  38. }
  39.  
  40.  
  41. int main() {
  42. string first[] = {"pale", "pales", "pale", "pale"};
  43. string second[] = {"ple", "pale", "bale", "bae"};
  44. for (int i = 0; i < 4; i++)
  45. cout << isOneAway(first[i], second[i]) << endl;
  46. return 0;
  47. }
Success #stdin #stdout 0s 4220KB
stdin
Standard input is empty
stdout
True
True
True
False