Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1c59665

Browse files
committed
Prob:182 find difference between strings
1 parent 280420a commit 1c59665

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
| Current Status| Stats |
88
| :------------: | :----------: |
9-
| Total Problems | 181 |
9+
| Total Problems | 182 |
1010

1111
</center>
1212

@@ -141,6 +141,7 @@ Include contains single header implementation of data structures and some algori
141141
| Implementation of Z algorithm for pattern matching | [z.cpp](string_problems/z.cpp)|
142142
| Test cases for self created string library | [pstring_test.cpp](string_problems/pstring_test.cpp)|
143143
| Get the length of the last word in a string. | [length_of_last_word.cpp](string_problems/length_of_last_word.cpp)|
144+
| Find the difference between two string. String t is generated by random shuffling string s and then add one more letter at a random position. Determine the character which is different in t| [find_difference.cpp](string_problems/find_difference.cpp)|
144145

145146
### Common Data Structure and logic problems
146147
| Problem | Solution |

‎string_problems/find_difference.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
* Find the difference between two string.
3+
* String t is generated by random shuffling string s and then add
4+
* one more letter at a random position.
5+
* Determine the character which is different in t.
6+
*
7+
* Approach: Since only one letter is different between s and t,
8+
* we could try XOR approach.
9+
* XOR of a character with itself will give 0.
10+
*/
11+
12+
#include <iostream>
13+
14+
char find_difference(const std::string& s, const std::string& t)
15+
{
16+
std::string r = s + t;
17+
char ch = 0;
18+
for (char c : r) {
19+
ch ^= c;
20+
}
21+
return ch;
22+
}
23+
24+
int main()
25+
{
26+
std::string str1{"hello"};
27+
std::string str2{"ollleh"};
28+
std::cout << "String 1: " << str1 << std::endl;
29+
std::cout << "String 2: " << str2 << std::endl;
30+
std::cout << "Diff: " << find_difference(str1, str2) << std::endl;
31+
return 0;
32+
}
33+
34+
35+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /