gpt4 book ai didi

java - 递归删除数组中所有相邻的重复数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:16 28 4
gpt4 key购买 nike

我想递归地删除数组中所有相邻的重复数字

我已经浏览过类似的链接,他们在字符串上执行此操作

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 来完成.

只需将数组中的每个数字放入堆栈,在堆栈顶部的每次迭代中检查重复数字,如果找到,则将其删除。

关于java - 递归删除数组中所有相邻的重复数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55318865/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com