这在 Java 中很容易解决。你只需要一个StringBuffer。这是完整的代码:
public class Test3 {
public static void main(String[] args) {
String str = "aaaabbbccdbbaae";
StringBuffer sbr = new StringBuffer();
int i = 0 ;
while(i < str.length()) {
if(sbr.length() == 0 ) sbr.append(str.charAt(i));
if(str.charAt(i) == sbr.charAt(sbr.length() -1)) {i++ ;}
else {sbr.append(str.charAt(i)); i++;}
}//while
System.out.println(sbr);
}
}//end1
这是 Python 中的完整解决方案:(不同的想法)
def lis(a):
list1 = []
# put the characters in the list
[list1.append(ch) for ch in a]
print(list1)
# moving backwards from last element i.e.len(a) -1 to first element 0 and step is -1
for i in range(len(list1) - 1 , 0 , -1):
# delete the repeated element
if list1[i] == list1[i - 1]: del list1[i]
return ''.join(list1)
a = "Protiijaayii"
# output Protijayi
print(lis(a))