大家好,我想问一下,我是否想检查数组是否有 4 个连续元素,就像这样 {1,2,4,4,4,4,3,5}
它将返回 true
但如果数组是 {1,2,4,4,4,2,4,2}
返回 false
请使用 Java 提供帮助:)}这是我的代码:
public class arraysearch {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr [] ={1,2,4,4,4,4,5,7,10};
int start = arr[0];
int count = 0;
int sum=0;
for(int i = 1;i<arr.length-1;i++)
{
if(start==4)
{
count++;
}
else
{
//count=0;
for(int j=i+1;j<arr.length-1;j++){
if(arr[i]==arr[j]&&arr[j]==4)
{
count++;
//continue;
}
}
}
}
if(count == 4)
{
System.out.println("it has 4 elements");
}
else
System.out.println("it hasn't 4 elements");
}
}
最佳答案
独特的解决方案,供引用:
int arr [] ={1,2,4,4,4,4,5,7,10};
for(int o : arr)
buffer.append(",").append(o);
boolean match = buffer.toString().matches("(\\d+)(?:,\\1){3}");
System.out.println("It "+(match ? "has" : "hasn't")+ " 4 elements");
您可以重用该模式以提高效率:
// Class
private static final Pattern CHAIN=Pattern.compile("(\\d+)(?:,\\1){3}");
// Method
int arr [] ={1,2,4,4,4,4,5,7,10};
for(int o : arr)
buffer.append(",").append(o);
System.out.println("It "+(CHAIN.matcher(buffer).matches() ? "has" : "hasn't")+ " 4 elements");
让我在这里解释一下这个魔法:
(\d+)(?:,\1){3}
是正则表达式。当数字序列在一行中出现四次(以逗号分隔)时,即匹配。这是分解后的样子:
> Capturing Group "\d+" one or more number digits
| > Non- Capturing Group: ",\1" a comma and a captured group
| | > The second group matches 3 times
| | |
(\d+)(?:,\1){3}
关于java - 检查数组是否有连续的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24059807/