面试上机题目: 写一个方法,把字符临近的‘<’和‘>’包围的内容及<>删除
例如:
<123>1<456>8<9</456></123> 输出:18<9
<2abc>7<df</2d>8></2abc> 输出:7
<123>4<456>>5<2ab>> 输出:4>5>
<1sd>qwe<<4fg>8>< 输出: qwe<
我的作答
(当时实际用时一小时 )
public static String subStr(String str) {
String back = str;
int left = -1;
boolean b = false;//尖括号 已<>完整 true不完整
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if ('<' == chars[i]) {
if (b) {
left = i;
} else {
b = true;
left = i;
}
}
if ('>'==chars[i]){
if (b){
b=false;
String ss= back.substring(left,i+1);
str=str.replace(ss,"");
str=subStr(str);
}
}
}
return str;
}