Diana sent a message "S" to agent 47 in an encrypted language so that no one else can decode it.
Now a string in the encrypted language is said to be valid if and only if it contains the characters '$' or '&' . Agent 47 decided to count the number of valid sub-strings of the message "S" sent by Diana.
P.S. - '$' and '&' characters are considered as 4 -> '$' and 7 -> '&' in a key-board.
Can you help Agent 47, in counting the total no. of valid substrings and the encrypted message.
Note: Two sub-strings are different if they occur at different positions in the message.
Example:
Input: s = "$bcd"
Output: 4
Approach
C++
#include <bits/stdc++.h>using namespace std;void fourtySevenString(string s){long long ans = 0, k = 0, count = 0;for (int i = 0; i < s.length(); i++){if (s[i] == '$' || s[i] == '&'){ans += (s.length() - i) * (count);ans += (s.length() - i);count = 0;}else{count++;}}cout << ans << "\n";}int main(){string s = "$bcd";fourtySevenString(s);return 0;}
No comments:
Post a Comment