You are given two strings s
and t
.
String t
is generated by the random shuffling string s
and then add one more letter at a random position.
Example 1:
Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter that was added.
Approach
Java
public class FindTheDifference {public static void main(String[] args) {String s = "ae";String t = "aea";System.out.println(findTheDifference(s, t));}// method to find different in two stringpublic static char findTheDifference(String s, String t) {char a = '\0';// iterate till end of stringfor (int i = 0; i < s.length(); i++) {a = s.charAt(i);// if second string is null then breakif (t.length() == 0)break;// replace first charactert = t.replaceFirst(String.valueOf(s.charAt(i)), "");}// if first less < secondif (t.length() != 0)return t.charAt(0);return a;}}
C++
#include <bits/stdc++.h>using namespace std;//find the different characters//all string contains only//lower case alphabetschar findTheDifference(string s, string t){int f[26]={0};for(int i=0;i<t.size();i++){f[t[i]-'a']++;}for(int i=0;i<s.size();i++)f[s[i]-'a']--;char ans;for(int i=0;i<26;i++)if(f[i]>0){ans=i+'a';break;}return ans;}int main(){string s="abcd";string t="abcde";char ch=findTheDifference(s,t);cout<<ch<<"\n";return 0;}
No comments:
Post a Comment