I was trying Leetcode problem https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/
It is to return minimum number of letters that needs to be changed to make the two strings anagrams. However when pass a string "leetcode" and other string "practise" , it should give output as 5 but giving 3.
LOGIC:
Could anybody help me in finding my mistake ?
class Solution {
public:
int minSteps(string s, string t) {
vector<char> v1;
char c;
int flag;
int val=0;
int count=0;
int len=0;
int sum=0;
int d=0;
int fsum=0;
for(int i=0;i<s.length();i++){
c=s[i];
flag=0;
vector<char> :: iterator it = find(v1.begin(),v1.end(),c);
if(it != v1.end()){
flag=1;
break;
}
else
if(flag==0){
v1.push_back(c);
len=s.length();
d=0;
val=0;
while(len){
if(c==s[d]) val++;
d++; len--;
}
//comparison in 2nd string
len=t.length();
d=0;
while(len){
if(c==t[d]) count++;
d++; len--;
}
if(val>count){
sum=val-count;
fsum+=sum;
val=count=0;
}
}
}
return fsum;
}
};
Your logic seems to be 'about' right. However, check the following piece of your code:
vector<char> :: iterator it = find(v1.begin(),v1.end(),c);
if(it != v1.end()){
flag=1;
break;
}
What this says is, if character c has already been seen before, BREAK out of the loop. I assume what you meant was CONTINUE with the next iteration of the loop.
This is because when you break, you do not break the loop over the vector v1 (I think that's what you assumed). Rather you break the loop over the string s.