• + 0 comments

    My logic is taking an char from s1 and find it in s2 and if found remove the part of s2 before that particular character and increment counter and repeat for next character from s1.

    Above iteration is done by taking character from s2 and finding them in s1.

    finnaly maximum of two methods is the answer

    Can anyone tell the mistake in my logic?

    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    
    public class Solution {
    
        static int commonChild1(String s1, String s2){
            int count=0;
            int nowfrom=0;
            String temp=s2;
            for(int i=0;i<s1.length();i++)
            {
                String finds=""+s1.charAt(i); //taking char from s1 
                            
                if(temp.contains(finds))//if tempcontians character than cut the part of string before that char in temp and increment count
                    
                {
                    nowfrom=temp.indexOf(finds)+1;
                    count++;
                }
                if(nowfrom>=temp.length())break;
                
                temp=temp.substring(nowfrom,temp.length());
                                   
            }        
            return count;
        }
        
        
        static int commonChild2(String s1, String s2){
            int array1[]=new int[26];
            int array2[]=new int[26];
            int count=0;
            int nowfrom=0;
            String temp=s1;
            for(int i=0;i<s2.length();i++)
            {
                String finds=""+s2.charAt(i);
                         
                if(temp.contains(finds))
                {
                    nowfrom=temp.indexOf(finds)+1;
                    count++;
                }
                if(nowfrom>=temp.length())break;
                
                temp=temp.substring(nowfrom,temp.length());                
                
            }
            
            return count;
        }
        
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            String s1 = in.next();
            String s2 = in.next();
            int result = Math.max(commonChild1(s1, s2),commonChild2(s1, s2));
            System.out.println(result);
        }
    }