题目:
如果字符串中只包含0和1,并且相邻字符不重复,那么该字符串被叫做交替字符串。例如:"1"、"10101"、"0101010101"
现在有一个字符串s,其中s中的每一个字符都是'0'
或者'1'
,请找出字符串s
中的最长交替子串的长度
代码:
public class Test {
public static void main(String[] args) {
// 测试数据
String s = "1101011";
// 开始测试
System.out.println(getMaxNum(s));
}
/**
* 获取最长交替子串的长度
*
* @param s 测试数据
* @return 最长交替子串的长度
*/
public static Integer getMaxNum(String s) {
// 最大交替子串的长度
int max = 0;
// 交替子串长度
int num = 1;
// 第一个字符
char ch = s.charAt(0);
// 遍历字符串中的所有字符
for (int i = 1; i < s.length(); i++) {
// 判断当前字符和前一个字符是否相等
if (s.charAt(i) == ch) {
// 获取最大交替子串长度
max = Math.max(max, num);
// 初始化交替子串长度
num = 1;
} else {
num++;
}
// 获取当前的字符,下一次if判断时候ch就变成了前一个字符
ch = s.charAt(i);
}
// 防止最大交替子串出现在最后的情况
max = Math.max(max, num);
// 返回最长交替子串长度
return max;
}
}
结果:
5
拓展:
如果想获得最长交替子串的值,代码如下:
public class Test {
public static void main(String[] args) {
// 测试数据
String s = "1101011";
// 开始测试
System.out.println(getMaxStr(s));
}
/**
* 获取最长交替子串
*
* @param s 测试数据
* @return 最长交替子串
*/
public static String getMaxStr(String s) {
// 最大交替子串的长度
int max = 0;
// 最长交替子串
String maxStr = "";
// 交替子串长度
int num = 1;
// 第一个字符
char ch = s.charAt(0);
// 遍历字符串中的所有字符
for (int i = 1; i < s.length(); i++) {
// 判断当前字符和前一个字符是否相等
if (s.charAt(i) == ch) {
// 获取最大交替子串长度
max = Math.max(max, num);
// 获取最长交替子串
if (max == num) {
maxStr = s.substring(i - num, i);
}
// 初始化交替子串长度
num = 1;
} else {
num++;
}
// 获取当前的字符,下一次if判断时候ch就变成了前一个字符
ch = s.charAt(i);
}
// 防止出现 最大交替子串在最后 或者 字符串中只有一个字符 的情况
max = Math.max(max, num);
// 获取最长交替子串
if (max == num) {
maxStr = s.substring(s.length() - num);
}
// 返回最长交替子串
return maxStr;
}
}