最长子字符串的长度(一)
标题:最长子字符串的长度(一) | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
给你一个字符串 s,字符串s首尾相连成一个环形 ,请你在环中找出 'o' 字符出现了偶数次最长子字符串的长度。
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int maxlen = findTheLongestSubstring(input);
System.out.println(maxlen);
}
static int findTheLongestSubstring(String s) {
int n = s.length();
int[] pos = new int[1 << 5];
Arrays.fill(pos, -1);
int ans = 0, status = 0;
pos[0] = 0;
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (ch == 'o') {
status ^= (1 << 3);
}
if (pos[status] >= 0) {
ans = Math.max(ans, i + 1 - pos[status]);
} else {
pos[status] = i + 1;
}
}
return ans;
}
}
from collections import Counter
s = input()
s_dic = Counter(s)
num = s_dic.get("o",0)
print(len(s) - 1 if num % 2 else len(s))
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String result = str.replaceAll("o", "");
if ((str.length() - result.length()) % 2 == 0) {
System.out.println(str.length());
} else {
System.out.println(str.length() - 1);
}
}
}
查看9道真题和解析
