我需要:
编写一个接受字符串并以整数形式返回输入中第二高数字的函数。
以下规则应适用:
没有数字的输入应返回-1
仅包含一个数字的输入应返回-1
应忽略非数字字符
每个数字输入应单独对待,这意味着 联合最高位数的事件,则第二高位数将 也是最高的数字
例如:
这是我当前的代码:
public class Solution {
public static int secondHighestDigit(String input) {
try{
int k = Integer.parseInt(input);
char[] array = input.toCharArray();
int big = Integer.MIN_VALUE;
int secondBig = Integer.MIN_VALUE;
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
for(int n = 0; n < array[i]; n++){
if(array[i] > big)
{
secondBig = big;
big = array[i];
}else if(array[i] > secondBig && array[i] != big){
secondBig = array[i];
}
}
}
System.out.println(secondBig);
}catch(Exception e) {
System.out.println("-1");
}
return -1;
}
}
测试:
import org.junit.*;
import static org.junit.Assert.*;
public class Tests
{
@Test
public void test1()
{
Solution solution = new Solution();
assertEquals(3, solution.secondHighestDigit("abc:1231234"));
}
@Test
public void test2()
{
Solution solution = new Solution();
assertEquals(3, solution.secondHighestDigit("123123"));
}
}
该程序应该为abc:1231234和123123打印3,但是相反,它们都返回-1。
我迷路了从这里去哪里。如果有人可以帮助我,我将不胜感激。谢谢。
答案 0 :(得分:3)
一种可能的解决方案是删除所有非数字字符并对字符串进行排序
public int secondGreatest(String s) {
String newStr = s.replaceAll("[^0-9]*", "");
if (newStr.isEmpty() || newStr.length() == 1) {
return -1;
} else {
char[] c = newStr.toCharArray();
Arrays.sort(c);
return c[newStr.length() - 2] - '0';
}
}
答案 1 :(得分:0)
首先不要尝试将字符串转换为Integer,因为您已经知道它可能包含一些非数字字符。
相反,解析字符串中的每个字符(如果它是整数),则将其添加到整数列表中。让我们使用ArrayList,以便我们可以添加到列表中并对其进行动态调整大小。
您的代码应如下所示:(给您一些工作要做)
// Iterate through characters in the string
// You could also use "substring" so you don't have to deal with chars
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(Character.isDigit(c)) {
// Convert c to an int appropriately and add it to your list of ints
}
}
// Sort the list of ints in descending order
// Now, we write a seperate method
public int getNthBiggest(int n) {
// Return the nth biggest item (you could just use 2)
}
如果您已经走了这么远,那么检查字符串是否包含0或1个“数字”应该对您来说是微不足道的。
答案 2 :(得分:0)
运行以下代码:
private static int secondHighestDigit(字符串输入){
String pattern = "(\\d+)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(input);
if (m.find( )) {
String foundedDigits = m.group(0);
System.out.println("Found value: " + m.group(0) );
char[] characters = foundedDigits.toCharArray();
List<Integer> integers = new ArrayList<>();
for(char c : characters){
integers.add(Integer.parseInt(c +""));
}
if(integers.size()==1)
return -1;
Collections.sort(integers);
System.out.println("One Biggest int: " + integers.get(integers.size()-1));
System.out.println("Two Biggest int: " + integers.get(integers.size()-2));
return integers.get(integers.size()-2);
}else {
System.out.println("NO MATCH");
return -1;
}
}