遍历字符串中的字符并删除连续的重复项 [英] Iterate through characters in a string and remove consecutive duplicates
本文介绍了遍历字符串中的字符并删除连续的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试遍历字符串并删除连续的重复字母.
I am trying to iterate through a string and remove consecutive duplicates letter.
ABBACBAABCB-->AACBAABCB-->CBAABCB-->CBBCB-->CCB-->B
我的想法是遍历字符串并删除 do-while 循环内的重复项.
My Idea was to iterate through the string and remove duplicates inside a do-while loop.
我的代码:
class Main {
public static String list = "ABBACBAABCB";
public static boolean notvalid = true;
public static void main(String[] args) {
do {
String r = Itterate(list);
isvalid(r);
//list = r does not work
} while (notvalid);
}
public static String Itterate(String str) {
for (int i = 1; i < list.length(); i = i + 1) {
char Curr = list.charAt(i);
char Prev = list.charAt(i - 1);
if (Curr == Prev) {
String results = str.substring(0, i - 1)
+ str.substring(i, str.length());
return results;
}
}
return str;
}
public static void isvalid(String str) {
for (int i = 1; i < str.length(); i = i + 1) {
char curr = str.charAt(i);
char prev = str.charAt(i - 1);
if (curr == prev) {
notvalid = true;
return;
}
}
notvalid = false;
return;
}
}
显然这是行不通的,它只会永远循环下去.
Obviously this doesn't work, it simply loop forever.
根据我的收集,由于字符串是不可变的,因此无法在Java上执行 list = results
.
From what I have gathered you can't do list = results
on java as string are immutable.
如何使用Java做到这一点?
How can this be done with Java?
推荐答案
您应该使用这样的堆栈.
You should use a stack like this.
static String removeConsecutiveDupplicatesLetter(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray())
if (!stack.isEmpty() && stack.peek() == c)
stack.pop();
else
stack.push(c);
return stack.stream().map(String::valueOf).collect(Collectors.joining());
}
还有
String s = "ABBACBAABCB";
System.out.println(removeConsecutiveDupplicatesLetter(s));
结果:
B
这是这样的.
stack c
------- -
[] A
[A] B
[A B] B
[A] A
[] C
[C] B
[C B] A
[C B A] A
[C B] B
[C] C
[] B
[B]
您也可以将 char []
用作堆栈,而不是 Stack
.
You can also use char[]
as a stack instead of Stack
.
static String removeConsecutiveDupplicatesLetter(String s) {
int length = s.length();
char[] stack = new char[length];
int index = 0;
for (char c : s.toCharArray())
if (index > 0 && stack[index - 1] == c)
--index;
else
stack[index++] = c;
return new String(stack, 0, index);
}
这篇关于遍历字符串中的字符并删除连续的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文