1.字符串中找出连续最长的数字串
读入一个字符串str,输出字符串str中的连续最长的数字串
public class Test1 {
public static String Solution1(List<String> list){
int max = 0;
int index = 0;
for(int i = 0;i<list.size();i++){
int num = list.get(i).length();
if(num>max){
max = num;
index = i;
}
}
return list.get(index);
}
public static List<String> Solution(String msg){
List<String> list = new ArrayList<>();
int i = 0;
int j = 0;
int len = msg.length();
while (i<len){
for(j = i;j<len;j++){
char s = msg.charAt(j);
if(s >='0'&&s<='9'){
}else {
break;
}
}
if(j != i){
String s1 = msg.substring(i,j);
list.add(s1);
}
i++;
}
return list;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String message = scanner.nextLine();
List<String> list = Solution(message);
String result = Solution1(list);
System.out.println(result);
}
}
2.合法括号序列判断
对于一个字符串,请设计一个算法,判断其是否为一个合法的括号串。
给定一个字符串A和它的长度n,请返回一个bool值代表它是否为一个合法的括号串。
public class Test3 {
public static boolean chkParenthesis(String A, int n) {
// write code here
Stack<Character> stack = new Stack<>();
char[] str = A.toCharArray();
for(int i = 0;i<n;i++){
switch (str[i]){
case '{':
case '(':
case '[':
stack.push(str[i]);
break;
case '}':
case ')':
case ']':{
if(stack.isEmpty()){
return false;
}
char ch = stack.pop();
if(!((ch=='{'&&str[i]=='}')||(ch=='('&&str[i]==')')||(ch=='['&&str[i]==']'))){
return false;
}
}
}
}
if(!stack.isEmpty()){
return false;
}
return true;
}
public static void main(String[] args) {
String A = "()(()()";
System.out.println(chkParenthesis(A,A.length()));
}
}