[英]Improving the run time and style of string compare method java?
I am trying to solve this problem: Write a function to check if two strings are the same length. 我正在尝试解决此问题:编写一个函数来检查两个字符串的长度是否相同。 If either string contains any numbers, those numbers are added to the length. 如果任一字符串包含任何数字,则将这些数字添加到长度中。 Ex: "ab2" & "aabb" //true "hhhsss" & "12" //false "hello" & "sarah" //true "2abc" & a1a1a" //true 例如:“ ab2”&“ aabb” // true“ hhhsss”&“ 12” // false“ hello”&“ sarah” // true“ 2abc”&a1a1a“ // true
This is my code, it works but its slow, repetitive, too wordy and less efficient than it should be. 这是我的代码,它可以运行,但是它的速度慢,重复性强,过于冗长且效率不高。 I'm a beginner and looking for tips on how to improve this. 我是一个初学者,正在寻找有关如何改善此问题的技巧。 Thanks in advance! 提前致谢!
public static boolean pattern(String a, String b) {
char A[] = a.toCharArray();
char B[] = b.toCharArray();
Arrays.sort(A);
Arrays.sort(B);
int i = 0;
int timesA = 0;
int lengthA = 0;
while (i < A.length && Character.isDigit(A[i])) {
lengthA += A[i];
timesA++;
i++;
}
lengthA += A.length - timesA;
int j = 0;
int timesB = 0;
int lengthB = 0;
while (j < B.length && Character.isDigit(B[j])) {
lengthB += B[j];
timesB++;
j++;
}
lengthB += B.length - timesB;
return lengthA == lengthB;
}
I would do some changes in your overall strategy. 我会对您的整体策略进行一些更改。
You do not neet to sort the two strings in the beginning. 您无需在开头对两个字符串进行排序。
Create four variables: a counter and a digit buffer for each string. 创建四个变量:每个字符串的计数器和数字缓冲区。
Loop over each char of the two strings and if it is: 循环遍历两个字符串中的每个字符,如果是:
a digit : concatenate the digit to the respective buffer 数字 :将数字连接到相应的缓冲区
not a digit : add 1 to the respective counter. 不是数字 :将1加到各自的计数器上。 Also, evaluate the respective buffer as a number and add the result to the counter. 同样,将相应的缓冲区评估为数字并将结果添加到计数器。 Empty the buffer. 清空缓冲区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.