java - 递归删除数组中所有相邻的重复数字
问题描述
我想递归删除数组中所有相邻的重复数字
我已经浏览过类似的链接,他们在字符串上执行此操作
https://www.geeksforgeeks.org/recursively-remove-adjacent-duplicates-given-string/
下面是删除字符串中相邻重复项的代码,我想知道是否有一种理想的方法可以沿着相同的路线运行,但在数组上运行它
static String removeUtil(String str, char last_removed)
{
// If length of string is 1 or 0
if (str.length() == 0 || str.length() == 1)
return str;
// Remove leftmost same characters and recur for remaining
// string
if (str.charAt(0) == str.charAt(1))
{
last_removed = str.charAt(0);
while (str.length() > 1 && str.charAt(0) == str.charAt(1))
str = str.substring(1, str.length());
str = str.substring(1, str.length());
return removeUtil(str, last_removed);
}
// At this point, the first character is definiotely different
// from its adjacent. Ignore first character and recursively
// remove characters from remaining string
String rem_str = removeUtil(str.substring(1,str.length()), last_removed);
// Check if the first character of the rem_string matches with
// the first character of the original string
if (rem_str.length() != 0 && rem_str.charAt(0) == str.charAt(0))
{
last_removed = str.charAt(0);
return rem_str.substring(1,rem_str.length()); // Remove first character
}
// If remaining string becomes empty and last removed character
// is same as first character of original string. This is needed
// for a string like "acbbcddc"
if (rem_str.length() == 0 && last_removed == str.charAt(0))
return rem_str;
// If the two first characters of str and rem_str don't match,
// append first character of str before the first character of
// rem_str
return (str.charAt(0) + rem_str);
}
假设输入数组是
1) [2,3,3] - 输出为 [2]
2) [1,2,3,3,2] - [1,2,2] - 输出为 [1]
3) [2, 0, 0, 2, 3, 3, 0, 0, 1, 1] - 输出为 []
编辑 - 如果有人仍在寻找解决方案,我想出了一个出路。我修复了 @kemalturgul 解决方案中的错误。这对我有用。
public static int[] removeUtil(int[] arr)
{
int i=0;
boolean check = false;
for (i = 0; i < arr.length - 1; i++)
{
if (arr[i] == arr[i + 1])
{
check = true;
break;
}
}
if(check)
return removeUtil(combineTwoArray(Arrays.copyOfRange(arr, 0, i), Arrays.copyOfRange(arr, i + 2, arr.length)));
else
return arr;
}
public static int[] combineTwoArray(int[] arr1, int[] arr2) {
int[] newArr = Arrays.copyOf(arr1, arr1.length + arr2.length);
for (int j = 0; j < arr2.length; j++)
newArr[arr1.length + j] = arr2[j];
return newArr;
}
解决方案
您可以简单地使用ArrayDeque来完成。
只需将数组中的每个数字放入堆栈,在堆栈顶部的每次迭代中检查重复的数字,如果找到,则将其删除。