Check if string s is a subsequence of string t.
Example:
Input: string s="abc" , t="ahbgdc"
Output: true
Approach
Java
public class IsSubsequence {public static void main(String[] args) {String s="abc";String t="ahbgdc";System.out.println(isSubsequence(s,t));}// function to check if string// is subsequence of other stringstatic boolean isSubsequence(String s, String t) {int n = s.length(), m = t.length();if (m < n)return false;int i = 0, j = 0;while (i < n && j < m) {if (s.charAt(i) == t.charAt(j)) {i++;j++;} elsej++;}if (i == n)return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check if string// is subsequence of other stringbool isSubsequence(string s, string t){int n=s.size(),m=t.size();if(m<n)return false;int i=0,j=0;while(i<n&&j<m){if(s[i]==t[j]){i++;j++;}elsej++;}if(i==n)return true;return false;}int main(){string s="abc";string t="ahbgdc";if(isSubsequence(s,t))cout<<"true\n";elsecout<<"false\n";return 0;}
No comments:
Post a Comment