1.next()与nextLine()之间的区别:
next()方法在读取内容时,会过滤掉有效字符之前的无效字符。对输入有效字符之前的空格键、tab键和enter键等结束键,next()方法会自动将其过滤,只有在读到有效字符之后遇到的空格键、tab键和enter键等才视为结束符。所以next()方法不能得到带空格的字符串
nextLine()字面上有扫描一行的意思,他的结束符只能是enter键,他是可以得到带空格的字符串的。
链接:https://www.nowcoder.com/questionTerminal/bd891093881d4ddf9e56e7cc8416562d
来源:牛客网
2.编程题
(1)字符串中找出连续最长的数字串
读入一个字符串str,输出字符串str中的连续最长的数字串
输入描述:
个测试输入包含1个测试用例,一个字符串str,长度不超过255。
输出描述:
在一行内输出str中里连续最长的数字串。
示例1
输入
abcd12345ed125ss123456789
输出
123456789
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.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 = "";
}
}
}
//处理最长字符串在最后面的情况,如ab23cde1234567
if(i == str.length() && cur.length() > ret.length() ){
ret = cur;
}
System.out.println(ret);
}
}
3.题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
示例1
输入
[1,2,3,2,2,2,5,4,2]
返回值
2
第一种解法:
1)先对数组进行排序
2)定义一个中间数值midNum,(如果有超过数组一半的数字,那么中间的这个数字一定就是)
3)遍历数组,计算等于midNum的次数count,如果count >数组长度的一半,这个数midNum就是超过数组长度一半的数字
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array == null || array.length == 0){
return 0;
}
Arrays.sort(array);//数组排序
int len = array.length;
int midNum = array[len / 2];
int count = 0;
for(int i = 0; i < array.length; i++){
if(array[i] == midNum){
count++;
}
}
if(count > len / 2){
return midNum;
}
return 0;
}
}
第二种解法:
众数与非众数
在数组中,如果两个数不相等,就消去这两个数,最坏情况下,每次消去一个众数和一个非众数,那么如果存在众数,最后留下的数肯定是众数。
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array == null || array.length == 0){
return 0;
}
int result = array[0];
int times = 1;//出现次数
for(int i = 1; i < array.length; i++){
if(times != 0){
if(array[i] == result){
times++;
}else{
times--;
}
}else{
//更新result的值为当前元素,并置times为1
result = array[i];
times = 1;
}
}
///判断result是否符合条件,即出现次数大于数组长度的一半
times = 0;
for(int i = 0; i < array.length; i++){
if(array[i] == result){
times++;
}
}
return (times > array.length / 2) ? result : 0;
}
}