网易笔试:交错01串
题目描述
如果一个01串任意两个相邻位置的字符都是不一样的,我们就叫这个01串为交错01串。例如: “1”,”10101”,”0101010”都是交错01串。
小易现在有一个01串s,小易想找出一个最长的连续子串,并且这个子串是一个交错01串。小易需要你帮帮忙求出最长的这样的子串的长度是多少。
输入描述:
输入包括字符串s,s的长度length(1 ≤ length ≤ 50),字符串中只包含’0’和’1’输出描述:
输出一个整数,表示最长的满足要求的子串长度。输入例子1:
111101111输出例子1:
3
思路:
扫描字符串,统计01交错的个数
java:
import java.util.Scanner;
public class Main {
public static int solution(String line) {
char[] c = line.toCharArray();
int max = 0;
int count = 0;
for(int i = 0; i < c.length - 1; i++) {
if((c[i] == '0' && c[i+1] == '1') ||
(c[i] == '1' && c[i+1] == '0') ) {
count++;
} else {
max = Math.max(max, count + 1);
count = 0;
}
}
max = Math.max(max, count + 1);
return max;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String line = sc.nextLine();
int result = solution(line);
System.out.println(result);
}
sc.close();
}
}
c++:
#include <iostream>
#include <string.h>
using namespace std;
int solution(string str) {
int len = str.length();
int count = 0, result = 0;
for(int i = 0; i < len - 1; i++) {
if((str[i] == '0' && str[i+1] == '1') ||
(str[i] == '1' && str[i+1] == '0') ){
count++;
}else {
result = max(result, count + 1);
count = 0;
}
}
result = max(result, count + 1);
return result;
}
int main() {
string str;
cin >> str;
int result = solution(str);
cout << result << endl;
return 0;
}
注:学渣心里苦,不要学楼主,平时不努力,考试二百五,哭~