删除字符串相邻两个元素---java
实现一个方法,给定一个输入字符串,能够删除所有连续同样字母(大小写不敏感)。例如,输入为ABBCCCCCBBAB,输出就是 ABCBAB
import java.util.ArrayList;
import java.util.stream.Collectors;
public class DemoTen {
public static void main(String[] args){
String str1 = "ABBCCCCCBBAB";
String str2 = "aAC";
String aa =dele(str1);
String bb =dele(str2);
System.out.println(aa);
System.out.println(bb);
}
private static String dele(String str1) {
String s1 = str1.toUpperCase();
int i=0,j=1;
ArrayList<Object> arrayList = new ArrayList<Object>();
for(int k=0;k<s1.length();k++) {
arrayList.add(s1.charAt(k));
}
System.out.println(arrayList.toString());
while(i<j&&i<arrayList.size()&&j<arrayList.size()) {
if(arrayList.get(i).equals(arrayList.get(j))) {
arrayList.remove(j);
}else {
i++;
j++;
}
}
String list = arrayList.stream().map(Object::toString).collect(Collectors.joining(""));
return list;
}
}
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.platform.commons.util.StringUtils;
public class DemoTen {
public static void main(String[] args){
String str1 = "ABBCCCCCBBAB";
String str2 = "aAC";
StringBuilder aa =dele(str1);
StringBuilder bb =dele(str2);
System.out.println(aa);
System.out.println(bb);
}
private static StringBuilder dele(String str1) {
String s1 = str1.toUpperCase();
int i=0,j=1;
ArrayList<Object> arrayList = new ArrayList<Object>();
for(int k=0;k<s1.length();k++) {
arrayList.add(s1.charAt(k));
}
System.out.println(arrayList.toString());
while(i<j&&i<arrayList.size()&&j<arrayList.size()) {
if(arrayList.get(i).equals(arrayList.get(j))) {
arrayList.remove(j);
}else {
i++;
j++;
}
}
StringBuilder stringBuilder = new StringBuilder();
for(Object character:arrayList) {
stringBuilder.append(character);
}
return stringBuilder;
}
}