You are given a DNA sequence: a string consisting of characters A, C, G, and T. Your task is to find the longest repetition in the sequence. This is a maximum-length substring containing only one type of character.
Example:
Input: s = "ATTCGGGA"
Output: 3
Approach
Java
public class Repetitions {public static void main(String[] args) {String s = "ATTCGGGA";System.out.println(repetitions(s));}static int repetitions(String s) {int n = s.length();int i = 0;int ans = 1;int cnt = 1;while (i < n) {cnt = 1;while (i < n - 1 && s.charAt(i) == s.charAt(i + 1)) {cnt++;i++;}i++;ans = Math.max(ans, cnt);}ans = Math.max(ans, cnt);return ans;}}
C++
#include <bits/stdc++.h>using namespace std;int repetitions(string s){int n = s.size();int i = 0;int ans = 1;int cnt = 1;while (i < n){cnt = 1;while (i < n - 1 && s[i] == s[i + 1]){cnt++;i++;}i++;ans = max(ans, cnt);}ans = max(ans, cnt);return ans;}int main(){string s = "ATTCGGGA";cout << repetitions(s);return 0;}
No comments:
Post a Comment