字符串中找出连续最长的数字串、合法括号序列判断

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()));
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值