Java算法:使用顺序栈判断字符串是否为“序列1@序列2”形式
本文提供Java代码,使用顺序栈判断给定字符串是否为'序列1@序列2'形式的合法字符串,其中'序列2'是'序列1'的逆序,且字符串中只有一个'@'字符。
import java.util.Stack;
public class StringCheck {
public static boolean isValidString(String str) {
Stack<Character> stack = new Stack<>();
int index = str.indexOf('@');
if (index == -1 || index != str.lastIndexOf('@')) {
// 如果没有'@'或有多个'@'字符
return false;
}
for (int i = 0; i < index; i++) {
stack.push(str.charAt(i));
}
for (int i = index + 1; i < str.length(); i++) {
if (stack.isEmpty() || str.charAt(i) != stack.pop()) {
// 如果'序列2'中的字符不是'序列1'的逆序
return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String str = "sequence1@1ecnues";
boolean isValid = isValidString(str);
System.out.println(isValid);
}
}
代码中,我们创建了一个栈,并遍历'序列1'('@'字符之前)的字符,将它们压入栈中。然后,我们遍历'序列2'('@'字符之后)的字符,检查它们是否与从栈中弹出(即'序列1'的逆序)的字符匹配。如果所有字符都匹配并且最终栈为空,则认为该字符串是有效的字符串。
原文地址: https://www.cveoy.top/t/topic/pin 著作权归作者所有。请勿转载和采集!