双指针

发布时间 2023-09-26 17:52:09作者: 爱新觉罗LQ

双指针

OD281 在字符串中找出连续最长的数字串(含“+-”号)

请在一个字符串中找出连续最长的数字串,并返回这个数字串。
如果存在长度相同的连续数字串,返回最后一个。
如果没有符合条件的字符串,返回空字符串””。
注意:
数字串可以由数字”0-9″、小数点”.”、正负号”±”组成,长度包括组成数字串的所有符号。
“.”、“±”仅能出现一次,”.”的两边必须是数字,”±”仅能出现在开头且其后必须要有数字。
长度不定,可能含有空格。

思路:当前值如果是 + 或者 - 的话,就意味着是一个新的开始
如果因为 . 超过 1 个的话,跳过第一个 .

import java.util.Scanner;
import java.util.*;


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        int len = Integer.MIN_VALUE;
        int count2 = 0;  //  记录:. 个数
        int[] res = new int[2];

        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        int l = 0;
        int r = 0;
        for (int i = 0; i < s.length(); i++) {
            r++;
            char c = s.charAt(i);
            if (!Character.isDigit(c) && c != '+' && c != '-' && c != '.'){
                l = r;
                count2 = 0;
            }

            if (c == '+' || c == '-' || c == '.'){
                if (c == '+' || c =='-'){   //  只能位于开头
                    l = i;
                    count2 = 0;
                }
                if (c == '.'){
                    if (!(i - 1 >= 0 && i + 1 < s.length() && Character.isDigit(s.charAt(i - 1)) && Character.isDigit(s.charAt(i + 1)))){
                        l = r;
                    }else {
                        count2++;
                    }
                }
            }

            if (count2 > 1){
                while (l < r){
                    char temp = s.charAt(l);
                    if (temp == '.'){
                        l++;
                        count2 -= 1;    //  跳过一个 . 
                        break;
                    }
                    l++;
                }
            }
            if (r - l >= len){
                len = r - l;
                if (len == 1){
                    char c1 = s.substring(l, r).charAt(0);
                    if (Character.isDigit(c1)){  //  有效数字
                        res[0] = l;
                        res[1] = r;
                    }
                }else {
                    res[0] = l;
                    res[1] = r;
                }
            }
        }
        String substring = s.substring(res[0], res[1]);
        if (substring.length() == 1 && !Character.isDigit(substring.charAt(0))){  //  特殊情况,只剩一个 +-.
            System.out.println("");
            return;
        }
        System.out.println(substring);    //  substring 不包含末尾!!!
    }
}