牛牛从生物科研工作者那里获得一段字符串数据s,牛牛需要帮助科研工作者从中找出最长的DNA序列。DNA序列指的是序列中只包括'A','T','C','G'。牛牛觉得这个问题太简单了,就把问题交给你来解决。
例如: s = "ABCBOATER"中包含最长的DNA片段是"AT",所以最长的长度是2。
输入包括一个字符串s,字符串长度length(1 ≤ length ≤ 50),字符串中只包括大写字母('A'~'Z')。
输出一个整数,表示最长的DNA片段
ABCBOATER
2
一种容易理解的解法,应该很容易看懂,这里就不解释了。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int max = 0;
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'A' ||
str.charAt(i) == 'T' ||
str.charAt(i) == 'C' ||
str.charAt(i) == 'G') {
count++;
max = Math.max(max, count);
} else {
count = 0;
}
}
System.out.println(max);
}
}
import java.util.Scanner; public class Main { public static int MaxLength(String s) { int count = 0; int maxLength = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'A' || s.charAt(i) == 'T' || s.charAt(i) == 'C' || s.charAt(i) == 'G') count++; else count = 0; if (count > maxLength) maxLength = count; } return maxLength; } public static void main(String[] args) { // 输入包括一个字符串s,字符串长度length(1 ≤ length ≤ 50),字符串中只包括大写字母('A'~'Z')。 Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String s = sc.nextLine(); System.out.println(MaxLength(s)); } } }