所以我有一个这样的案例
<> = 1
<><> = 2
<<>> = 2
<<test<> = 1
如何使用正则表达式找到“<>”中的所有“<>”?
这是我尝试过的代码。
import java.io.IOException;
import java.util.regex.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
Pattern p = Pattern.compile("<(.*?)>");
Matcher m = p.matcher(input);
int count = 0;
while(m.find()){
count++;
}
System.out.println(count);
}
}
从count
变量和空堆栈开始。您应该使用stack
,迭代每个字符来解决这个问题,当您找到<
将其推入堆栈时,您找到的时间>
,在堆栈不为空时从堆栈中弹出并增加您的计数。
编辑:使用堆栈
import java.util.*;
public class Test {
public static void main(String[] args) {
Stack<String> myStack = new Stack<String>();
String str = "<<test<> = 1 <><>";
int count=0;
char[] chs = str.toCharArray();
for(char ch: chs){
if(ch == '<'){
myStack.push(String.valueOf(ch));
}
if( !myStack.isEmpty() & (ch == '>')){
myStack.pop();
count++;
}
}
System.out.println("count = "+count);
}
}
输出
count = 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句