您可以通过消除您的 isNum() 方法并使用内置的 Character.isDigit() 方法来开始提高代码的速度。
您可以通过使用正则表达式从每个标记中提取数字而不是使用循环来进一步提高速度。
祝你好运。
编辑
比较这里一些答案的表现,似乎@Prabhakaran 的答案比原来的要慢,而@OldCurmudgeon 的更快,@Adam Stelmaszczyk 的最快:
import java.util.*;
public class TestSum {
public static int doSum(String str){
String[] sArray = str.split(" ");
char[] chr = null;
String temp;
String number = "";
int sum=0;
for(String s : sArray){
chr = s.toCharArray();
for(char c : chr){
temp = String.valueOf(c);
if(isNum(temp)){
number = number + temp;
}
}
sum = sum + Integer.parseInt(number);
number="";
}
return sum;
}
public static boolean isNum(String nStr){
try{
Integer.parseInt(nStr);
return true;
}catch(NumberFormatException nfe){
return false;
}
}
public static void testSum1(){
String str = "abc123 ws32wd3 y3tg43 5tga89 a1a";
str = str.replaceAll("[^0-9]+", " ");
List<String> asList = Arrays.asList(str.trim().split(" "));
int sum=0;
for (String string : asList) {
sum+=Integer.parseInt(string);
}
System.out.println(sum);
}
public static int doSum2(String str) {
int sum = 0;
// -1 means not started.
int start = -1;
for ( int i = 0; i < str.length(); i++ ) {
char ch = str.charAt(i);
if ( Character.isDigit(ch)) {
if ( start == -1 ) {
// Start of a number.
start = i;
}
} else {
if ( start != -1 ) {
// End of a number.
sum += Integer.parseInt(str.substring(start, i));
start = -1;
}
}
}
if ( start != -1 ) {
// A number at the end of the string.
sum += Integer.parseInt(str.substring(start, str.length()));
}
return sum;
}
public static int getSum(String str) {
int sum = 0;
int exp = 1;
for (int i = str.length() - 1; i >= 0; i--) {
final char c = str.charAt(i);
if (c >= '0' && c <= '9'){
sum += (c - '0') * exp;
exp *= 10;
}
else{
exp = 1;
}
}
return sum;
}
public static void main(String[] args) {
long startTime = System.nanoTime();
TestSum.testSum1();
long endTime = System.nanoTime();
System.out.println("testSum1 took " + (endTime - startTime) + " nanoseconds");
startTime = System.nanoTime();
System.out.println(TestSum.doSum("abc123 ws32wd3 y3tg43 5tga89 a1a"));
endTime = System.nanoTime();
System.out.println("doSum took " + (endTime - startTime) + " nanoseconds");
startTime = System.nanoTime();
System.out.println(TestSum.doSum2("abc123 ws32wd3 y3tg43 5tga89 a1a"));
endTime = System.nanoTime();
System.out.println("doSum2 took " + (endTime - startTime) + " nanoseconds");
startTime = System.nanoTime();
System.out.println(TestSum.getSum("abc123 ws32wd3 y3tg43 5tga89 a1a"));
endTime = System.nanoTime();
System.out.println("getSum took " + (endTime - startTime) + " nanoseconds");
}
}
这是输出
Davids-MacBook-Air:desktop dave$ javac TestSum.java
Davids-MacBook-Air:desktop dave$ java TestSum
299
testSum1 took 1790000 nanoseconds
1379
doSum took 373000 nanoseconds
299
doSum2 took 173000 nanoseconds
299
getSum took 45000 nanoseconds