Monthly Archives: February 2022
C# || How To Find The Difference Between Two Strings Using C#
The following is a module with functions which demonstrates how to find the difference between two strings using C#.
1. Find The Difference – Problem Statement
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.
Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.
Example 2:
Input: s = "", t = "y"
Output: "y"
2. Find The Difference – Solution
The following is a solution which demonstrates how to find the difference between two strings.
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 6, 2022 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find the difference between two strings // ============================================================================ public class Solution { public char FindTheDifference(string s, string t) { var result = ' '; // Create a map with the frequency each character has been seen from the first string var seen = new Dictionary<char, int>(); foreach (var letter in s) { seen[letter] = (seen.ContainsKey(letter) ? seen[letter] : 0) + 1; } // Decrease the frequency of the characters we've seen from the second string foreach (var letter in t) { // Either we havent seen this character, or its frequency has reached 0 if (!seen.ContainsKey(letter) || seen[letter] == 0) { result = letter; break; } // Decrease the frequency --seen[letter]; } return result; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
"e"
"y"