leetcode - 389 Find the Difference

 in there are given two strings s and t. string t is generated by random shuffling by random shuffling string s and then add one more letter at random position we need to write the logic to find the letter that was added in t and we return it

in this problem there all are in string s and t are small alphabets there ascii values start from 97 to 122 like this 

a=97,b=98,c=99........z=122 so let us assume s is source/starting and t is target/end in my approuch is prity simple adding sum of the source/ strating string in sum (int variable) and sum of target/end of in sum1(int variable) lets exaplain with example

input: s="abcd" and t="abcde"

output:"e"

explination:

in sum= a(97)+b(98)+c(99)+d(100)

total sum of ascii values of char in string s is  394 that store in sum=394

in sum1=a(97)+b(98)+c(99)+d(100)+e(101)

total sum of ascii values of char in string t is 495 that strore in sum1=495

the difference between sum1-sum is dif=495-394=>101 that ascii value of "e" but it is in integer data type 

we need string/char data type so we need to data typecasting 

this is the code in C++:

   class Solution {
public:
    char findTheDifference(string s, string t) {
      int sum=0;//intulsing the strating(s) string sum
      int sum1=0;//intulsing the target(t) string sum1
      int i;
      int n=s.size();//finding the size/how many elements are there
      int m=t.size();
      for(i=0;i<n;i++){
          sum+=s[i];//sum of each ascii value of string(s)
          }
      for(i=0;i<m;i++){
        sum1+=t[i];//sum of each ascii value elements of string(t)      
        }
        return (char)sum1-sum;//(char)by using this we datatype casting

    }
};

Post a Comment

0 Comments