A space explorer's ship crashed on Mars! They send a series of SOS
messages to Earth for help.
Letters in some of the
SOS
messages are altered by cosmic radiation during transmission. Given the signal received by Earth as a string,s, determine how many letters of the SOS message have been changed by the radiation.Example:
Input: s="SOSSOT"
Output: 1
Approach
Java
public class MarsExploration {public static void main(String[] args) {String s = "SOSSOT";int result = marsExploration(s);System.out.println(result);}private static int marsExploration(String s) {int i = 0, cnt = 0, n = s.length();while (i < n) {if (s.charAt(i) == 'S' && s.charAt(i + 1) == 'O' && s.charAt(i + 2) == 'S')i += 3;else if (s.charAt(i) == 'S' && s.charAt(i + 1) == 'O' && s.charAt(i + 2) != 'S') {i += 3;cnt++;} else if (s.charAt(i) == 'S' && s.charAt(i + 1) != 'O' && s.charAt(i + 2) == 'S') {cnt++;i += 3;} else if (s.charAt(i) != 'S' && s.charAt(i + 1) == 'O' && s.charAt(i + 2) == 'S') {cnt++;i += 3;}else if (s.charAt(i) == 'S' && s.charAt(i + 1) != 'O' && s.charAt(i + 2) != 'S') {cnt += 2;i += 3;}else if (s.charAt(i) != 'S' && s.charAt(i + 1) == 'O' && s.charAt(i + 2) != 'S') {cnt += 2;i += 3;}else if (s.charAt(i) != 'S' && s.charAt(i + 1) != 'O' && s.charAt(i + 2) == 'S') {cnt += 2;i += 3;} else if (s.charAt(i) != 'S' && s.charAt(i + 1) != 'O' && s.charAt(i + 2) != 'S') {cnt += 3;i += 3;}}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;int marsExploration(string s){int i = 0, cnt = 0, n = s.size();while (i < n){if (s[i] == 'S' && s[i + 1] == 'O' && s[i + 2] == 'S')i += 3;else if (s[i] == 'S' && s[i + 1] == 'O' && s[i + 2] != 'S'){i += 3;cnt++;}else if (s[i] == 'S' && s[i + 1] != 'O' && s[i + 2] == 'S'){cnt++;i += 3;}else if (s[i] != 'S' && s[i + 1] == 'O' && s[i + 2] == 'S'){cnt++;i += 3;}else if (s[i] == 'S' && s[i + 1] != 'O' && s[i + 2] != 'S'){cnt += 2;i += 3;}else if (s[i] != 'S' && s[i + 1] == 'O' && s[i + 2] != 'S'){cnt += 2;i += 3;}else if (s[i] != 'S' && s[i + 1] != 'O' && s[i + 2] == 'S'){cnt += 2;i += 3;}else if (s[i] != 'S' && s[i + 1] != 'O' && s[i + 2] != 'S'){cnt += 3;i += 3;}}return cnt;}int main(){string s = "SOSSOT";int result = marsExploration(s);cout << result << "\n";return 0;}
No comments:
Post a Comment