Posts

Search

I M07 - Discover the Substring

strstr is a function that returns 1 if one string is present as substring in another and 0 otherwise. You are to write a program to print the number of times one string is present in the other as a substring.
Input Format
Two lines of input consisting of two strings.
Constraints
1 <= length of strings <= 100
Output Format
Output one number, the number of times any one string appears in the other.
Sample Input 0
banana
ana
Sample Output 0
2
Explanation 0
b(ana)na and ban(ana) so answer is 2
Sample Input 1
a
adamant
Sample Output 1
3
Explanation 1
(a)damant, ad(a)mant and adam(a)nt. So answer is 3.
SOLUTION :-
import java.util.*;
public class Solution { 
    static int countFreq(String pat, String txt) {        
        int M = pat.length();        
        int N = txt.length();        
        int res = 0;
        for (int i = 0; i <= N - M; i++) {
            int j;            
            for (j = 0; j < M; j++) {
                if (txt.charAt(i + j) != pat.charAt(j)) {
                    break;
                }
            }
            if (j == M) {                
                res++;                
                j = 0;                
            }            
        }        
        return res;        
    }
    static public void main(String[] args) {
        Scanner in=new Scanner(System.in);
        String txt = in.nextLine();      
        String pat = in.nextLine();    
        if(txt.length()>pat.length()){
            System.out.println(countFreq(pat, txt));
        }
        else{
            System.out.println(countFreq(txt, pat));
        }    
    }