【牛客网】OR59 字符串中找出连续最长的数字串

题目

【牛客网】OR59 字符串中找出连续最长的数字串_第1张图片

思路

  1. 创建两个字符串 temp 和 ret 创建指针i用来遍历字符串
  2. 通过i遍历字符串,如果遇到数字则将这个数组加到字符串temp中 i++,如果遇到字母,则判断temp字符串的长度和ret字符串的长度,如果tempret则说明此时temp字符串是暂时的最大值,就将temp 的值赋给ret
  3. 遍历字符串结束,ret中存在的字符串就是我们想要的结果

代码

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String ret = "";
        String temp = "";
        String str = in.nextLine();
        int i = 0;
        while(i < str.length()){
            if(Character.isDigit(str.charAt(i))){
                temp += str.charAt(i);
            }else{
                if(temp.length()>ret.length()){
                    ret = temp;
                }
                temp = "";
            }
            i++;
        }
        if(temp.length()>ret.length()){
                    ret = temp;
                }
        System.out.print(ret);
    }
}

你可能感兴趣的:(算法,牛客网,java,开发语言)