Implement strStr()
Return the index of the first occurrence of needle in a haystack, or -1
if needle
is not part of haystack
.
Example
Input : text="hello", pattern="ll"
Output: Found at 2
Approach:
Java
public class ImplementstrStr {public static void main(String[] args) {String text = "hello";String pattern = "ll";int index = strStr(text, pattern);if (index == -1)System.out.println("Not found");elseSystem.out.println("Found at " + index);}// method to find the pattern string// into the text stringprivate static int strStr(String text, String pattern) {int n = text.length(), m = pattern.length();for (int i = 0; i <= n - m; i++) {int j;for (j = 0; j < m; j++)if (text.charAt(i + j) != pattern.charAt(j))break;if (j == m)return i;}return -1;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the pattern string//into the text stringint strStr(string text, string pattern){int n=text.size(),m=pattern.size();for(int i=0;i<=n-m;i++){int j;for(j=0;j<m;j++)if(text[i+j]!=pattern[j])break;if(j==m)return i;}return -1;}int main(){string text="hello";string pattern="ll";int index=strStr(text,pattern);if(index==-1)cout<<"Not found";elsecout<<"Found at "<<index<<"\n";return 0;}
No comments:
Post a Comment