用Java实现字符串匹配算法:代码示例及优化
当然,可以将上述代码用Java进行改写。以下是将其转换为Java的代码示例:
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static String isValid(String str) {
Stack<Character> strs = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (strs.empty()) {
strs.push(ch);
} else {
if (strs.peek() == 'a' && ch == 'b') {
strs.pop();
} else {
strs.push(ch);
}
}
}
return strs.empty() ? "Yes" : "No";
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0) {
String temp = scanner.next();
System.out.println(isValid(temp));
}
}
}
以上是将C++代码转换为Java代码的示例。请注意,转换后的代码可能仍然需要进行进一步的调试和测试,以确保其正确性和符合预期的行为。
原文地址: https://www.cveoy.top/t/topic/x7R 著作权归作者所有。请勿转载和采集!