We say that a string contains the word hackerrank
if a subsequence of its characters spell the word hackerrank
. Remember that a subsequence maintains the order of characters selected from a sequence.
More formally, let be the respective indices of h
, a
, c
, k
, e
, r
, r
, a
, n
, k
in string . If is true, then contains hackerrank
.
Example:
Input: s="hhaacckkekraraannk"
Output: YES
Approach
Java
import java.util.ArrayList;import java.util.List;public class HackerRankString {public static void main(String[] args) {String s = "hhaacckkekraraannk";String result = hackerrankInString(s);System.out.println(result);}private static String hackerrankInString(String s) {int n = s.length();int i = 0;List<Character> res = new ArrayList<Character>();while (i < n && s.charAt(i) != 'h')i++;if (i < n)res.add(s.charAt(i));i = i + 1;while (i < n && s.charAt(i) != 'a')i++;if (i < n)res.add(s.charAt(i));i++;while (i < n && s.charAt(i) != 'c')i++;if (i < n)res.add(s.charAt(i));i++;while (i < n && s.charAt(i) != 'k')i++;if (i < n)res.add(s.charAt(i));i++;while (i < n && s.charAt(i) != 'e')i++;if (i < n)res.add(s.charAt(i));i++;while (i < n && s.charAt(i) != 'r')i++;if (i < n)res.add(s.charAt(i));i++;while (i < n && s.charAt(i) != 'r')i++;if (i < n)res.add(s.charAt(i));i++;while (i < n && s.charAt(i) != 'a')i++;if (i < n)res.add(s.charAt(i));i++;while (i < n && s.charAt(i) != 'n')i++;if (i < n)res.add(s.charAt(i));i++;while (i < n && s.charAt(i) != 'k')i++;if (i < n)res.add(s.charAt(i));i++;if (res.size() == 10)return "YES";return "NO";}}
C++
#include <bits/stdc++.h>using namespace std;string hackerrankInString(string s){int n = s.size();int i = 0;vector<char> res;while (i < n && s[i] != 'h')i++;if (i < n)res.push_back(s[i]);i = i + 1;while (i < n && s[i] != 'a')i++;if (i < n)res.push_back(s[i]);i++;while (i < n && s[i] != 'c')i++;if (i < n)res.push_back(s[i]);i++;while (i < n && s[i] != 'k')i++;if (i < n)res.push_back(s[i]);i++;while (i < n && s[i] != 'e')i++;if (i < n)res.push_back(s[i]);i++;while (i < n && s[i] != 'r')i++;if (i < n)res.push_back(s[i]);i++;while (i < n && s[i] != 'r')i++;if (i < n)res.push_back(s[i]);i++;while (i < n && s[i] != 'a')i++;if (i < n)res.push_back(s[i]);i++;while (i < n && s[i] != 'n')i++;if (i < n)res.push_back(s[i]);i++;while (i < n && s[i] != 'k')i++;if (i < n)res.push_back(s[i]);i++;if (res.size() == 10)return "YES";return "NO";}int main(){string s = "hhaacckkekraraannk";string result = hackerrankInString(s);cout << result << "\n";return 0;}
No comments:
Post a Comment