如何使用我的代码找到最接近中间的点(基于询问的点数)



所以我有以下代码,我需要找到最接近行中间的非"#"的点数。由于在这种情况下我正在寻找 3 个点,我需要找到最靠近中间的 3 个点并获得这 3 个点的起始索引。我需要 3 个点彼此相邻。如果我需要更改字符串并且我需要更改要查找的点数,则无法对其进行硬编码。

int numOfDots = 3;
String line = "...#.#...#";
for (int i =0; i < line.length(); i++) {
}

##..##...#  //Index of 6 for 3 consecutive dots closest to middle
....#..### //Index of 1 
#..#..##.. //None
..##.....# //Index of 4(the middle column)
...#.#...# //Index of 6

你可以试试:

int numOfDots = 3;
String line = "...#.#...#";
String[] arry = line.split("#");
int middle = arry.length%2==0?arry.length/2:(arry.length/2 +1);
for (int i=middle,j = middle; i >= 0; i--,j++) {
if(arry[i].length()==numOfDots) {
System.out.println("Result Index in arry :" + i);
break;
}
if(j<arry.length&&arry[j].length()==numOfDots) {
System.out.println("Result Index in arry :" + j);
break;
}
}

最新更新