编程题
在字符串中找出连续最长的数字串
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine();
String str1 = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 0 && str.charAt(i) <= 9) {
str1 += str.charAt(i);
} else {
str1 += a;
}
}
String[] str2 = str1.split("a");
int max = 0;
for (int i = 0; i < str2.length; i++) {
max = str2[i].length() > max ? str2[i].length() : max;
}
for (int i = 0; i < str2.length; i++) {
if (max == str2[i].length()) {
System.out.println(str2[i]);
}
}
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String cur = "";
String ret = "";
int i = 0;
for ( ;i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 0 && ch <= 9) {
cur = cur + ch + "";
} else {
if (cur.length() > ret.length()) {
ret = cur;
} else {
cur = "";
}
}
}
if (i == str.length() && cur.length() > ret.length()) {
ret = cur;
}
System.out.println(ret);
}
}
数组中出现次数超过一半的数字
public int MoreThanHalfNum_Solution(int[] numbers) {
// write code here
Arrays.sort(numbers);
int count = 0;
int mid = numbers.length / 2;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == numbers[mid]) {
count++;
}
}
if (count > mid) {
return numbers[mid];
}
return 0;
}
public int MoreThanHalfNum_Solution1(int[] numbers) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(numbers[i])) {
map.put(numbers[i], map.get(numbers[i] + 1));
} else {
map.put(numbers[i], 1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > numbers.length / 2) {
return entry.getValue();
}
}
return 0;
}