首页 > 试题广场 >

字符串中找出连续最长的数字串

[编程题]字符串中找出连续最长的数字串
  • 热度指数:41264 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
读入一个字符串str,输出字符串str中的连续最长的数字串

输入描述:
个测试输入包含1个测试用例,一个字符串str,长度不超过255。


输出描述:
在一行内输出str中里连续最长的数字串。
示例1

输入

abcd12345ed125ss123456789

输出

123456789
//C++也可以很简洁
#include<iostream> #include<string> using namespace std; int main() {     string str,res,cur;     cin>>str;     for(int i=0;i<=str.length();i++){         if(str[i]>='0' && str[i]<='9')cur+=str[i];         else{             if(res.length()<cur.length())res=cur;             cur="";         }     }     cout<<res;     return 0; }

编辑于 2018-07-20 23:58:57 回复(9)

华为的笔试考的这道题:
python解法如下:

a = input()
maxLen, curLen, maxStr, curStr = 0, 0, "", ""

for i, v in enumerate(a):
    if v.isnumeric():
        curLen += 1
        curStr += v
        if curLen >= maxLen:
            maxLen = curLen
            maxStr = curStr
    else:
        curLen = 0
        curStr = ""
print(maxStr)
编辑于 2017-09-07 13:59:50 回复(4)
#include <stdio.h>
#include <string.h> 
int main(){
	int i,k,key,sum,max,len[300];
	char a[300];
	scanf("%s",a);
	for(int j=0;j<300;j++){		//初始化长度数组 
		len[j]=0;
	}
	for(i=0;i<strlen(a);i++){	
		k=i;
		sum=0;
		while(a[i]>='0' && a[i]<='9'){
			i++;
			sum++;
		}
		len[k]=sum;	//将每个位置出现的数组串长度,保存在len[]中,没出现的为 0 
	}
	max=0;
	for(i=0;i<strlen(a);i++){
		if(max<len[i]){
			max = len[i]; //保存最长的数字串长度 
			key = i;	//记录最长数字串, 初始地址 
		}
	}
	for(i=0;i<max;i++){	//从key下标输出,max个数字 
		printf("%c",a[key++]);
	} 
	printf("\0");
	printf("\n");
	return 0;
} 

发表于 2017-02-24 22:33:07 回复(0)

#include <iostream>

#include <string>

using namespace std;


int main()

{

    // insert code here...

    string str;

    cin>>str;

    string res;

    int length=0;

    int pos=0;

    for(int i=0,j=0;j<str.size();)

    {

        if(str[j]<'0' || str[j]>'9')

        {

            ++j;

            i=j;

        }

        else

        {

            ++j;

            if((j-i)>length)

            {

                pos=i;

                length=j-i;

            }

        }

    }

    res=str.substr(pos,length);

    cout<<res;

}
思路:双指针,遇到数字的时候,更新pos起始位置和子串的长度
发表于 2018-07-12 01:37:24 回复(2)
<?php
$str=trim(fgets(STDIN));
$len=strlen($str);
preg_match_all("/[0-9]+/",$str,$num);
$max=$num[0][0];
for($i=0;$i<count($num[0]);$i++)
{
    if($num[0][$i]>$max) $max=$num[0][$i];    
}
echo $max;

发表于 2017-09-16 16:34:39 回复(0)
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); String string=in.next(); System.out.println(findMaxDigits(string)); } private static String findMaxDigits(String string) { int tempMax=0; int max=0; String result=""; char[] ch=string.toCharArray(); StringBuilder sb=new StringBuilder(); for(int i=0;i<ch.length;i++){ if(Character.isDigit(ch[i])){ sb.append(ch[i]); tempMax++; }else{ tempMax=0; sb.delete(0, sb.length()); } if(max<tempMax){ max=tempMax; result=sb.toString(); } } return result; } }
编辑于 2017-02-17 23:54:35 回复(6)
Python
n = input().strip()
ans,temp = [],[]
for i in n:
    if 48 <= ord(i) <= 57:
        temp.append(i)
    else:
        ans.append(temp)
        temp = []
ans.append(temp)
ans = sorted(list(filter(None,ans)),key = len)
print(''.join(ans[-1]))

发表于 2018-07-08 22:32:24 回复(0)
let line = readline();
let arr = line.charAt(0);
let max = "";
for(let j = 1;j<line.length;j++){
if(arr.charCodeAt(arr.length-1)+1==line.charCodeAt(j)){
arr = arr+line.charAt(j);

}else{
arr = line.charAt(j);
}
if(max.length<=arr.length){
max = arr;
}
}
console.log(max);

编辑于 2018-10-09 17:29:16 回复(0)
strs = input()
res,ans,temp,tans,fans = 0,0,[],[],''
for i in strs:
    if i.isdigit():
        res+=1
        temp.append(int(i))
    elif not i.isdigit():
        if ans<res:
            ans = res
            tans = temp
            res = 0
            temp = []
        else:
            res = 0
            temp = []
if strs[-1].isdigit():
    if ans<res:
        ans = res
        tans = temp
for i in tans:
    fans += str(i)
print(fans)        
发表于 2021-05-18 20:11:18 回复(1)
import java.util.Scanner;

public class Main {

	//获取最长的连续数字串
	public static String maxDigitalStr(String str){
		char[] arrayChar = str.toCharArray();//将str转换成字符数组
		int maxDigiStrLen = 0;//最长连续数字串的长度
		String maxDigiStr = "";//最长连续数字串
		int tempStrLen = 0;//临时数字串长度
		StringBuffer tempStr = new StringBuffer();//临时数字串
		for(int i = 0; i < arrayChar.length; i++){
			//过滤掉非数字的字符
			if(arrayChar[i] >= '0' && arrayChar[i] <= '9'){
				tempStr.append(arrayChar[i]);
				tempStrLen++;
				if(tempStrLen > maxDigiStrLen){
					maxDigiStrLen = tempStrLen;//更新 最长连续数字串长度
					maxDigiStr = tempStr.toString();//更新 最长连续数字串
				}
			}else{
				tempStrLen = 0;//临时数字串长度 置0
				tempStr.setLength(0);//临时数字串 清空
			}
		}
		return maxDigiStr;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String tempStr = sc.next();
		System.out.println(maxDigitalStr(tempStr));
	}

}

编辑于 2020-07-22 22:55:48 回复(0)
直接新建一个一维数组,存放升序的累计个数,然后找最大,并往前输出最大长度的子字符串即为所求
while True:
    try:
        s=input()
        res=[1 for i in range(len(s))]
        for i in range(1,len(s)):
            if ord(s[i])==ord(s[i-1])+1:
                res[i]=res[i-1]+1
        mmax=max(res)
        ind=res.index(mmax)
        print(s[ind+1-mmax:ind+1])
    except:
        break

发表于 2019-09-23 21:19:42 回复(0)
import re
input_val = input()
split_char = re.split(r'\D*', input_val)
lst = []
for i in split_char:
    lst.append(len(i)) 
print(split_char[lst.index(max(lst))])

''' 
max(lst)找出lst中最大的元素的值
lst.index(max(lst))找出max(lst)找出lst中最大的元素的值”对应的索引
lst的大小和split_char是一致的,所以直接在split_char使用索引即可
'''

发表于 2019-08-04 13:52:28 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string a;
    cin>>a;
    int j=0;
    int count=0;
    int max=0;
    int maxi;
    for(int i=0;a[i]!='\0';i++)
    {
        if((int)a[i]<58&&(int)a[i]>47)    //判断是不是0-9的数字
        {
            count++;
            if(count>max)
            {
                max=count;              //记录最大长度
                maxi=i;                 //记录最大长度的结尾坐标
            }
        }
        else                              //不满足条件,重新计数
        {
            count=0;
        }
    }
    for(int i=maxi-max+1;i<=maxi;i++)          
    {
        cout<<a[i];
    }
}

发表于 2019-04-21 20:26:11 回复(0)
/*
使用两个字符串,字符串sb记录当前数字串及长度,strTemp记录下一个数字串及长度,如
果strTemp长度比sb长,则替换sb,即sb=strTemp,最后输出sb
*/
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            StringBuilder sb = new StringBuilder("");
            StringBuilder strTemp = new StringBuilder();
            char[] ch = sc.nextLine().toCharArray();
            for(int i=1;i<ch.length;i++){
                if(ch[i]>='0' && ch[i]<='9'){
                    strTemp.append(ch[i]);
                }
                if(ch[i]<'0' || ch[i] >'9' || i == ch.length-1){
                    if(strTemp.length()>sb.length()){
                        sb = strTemp;
                    }
                    strTemp = new StringBuilder("");
                }
            }
            System.out.println(sb);
        }
    }
}

发表于 2018-10-09 11:16:50 回复(0)
import java.util.ArrayList; import java.util.Scanner;  public class Solution30 { public static String MaxSubArray(char[] chars, int n) { if (n == 0) { return "";  }
        ArrayList<Character> curSum = new ArrayList<>();  ArrayList<Character> maxSum = new ArrayList<>();  StringBuilder sb = new StringBuilder();  for (int i = 0; i < n; i++) { if (Character.isDigit(chars[i])) {
                curSum.add(chars[i]);  } else { if (curSum.size() > maxSum.size()) {
                    maxSum.clear();  for (int j = 0; j < curSum.size(); j++) {
                        maxSum.add(curSum.get(j));  }
                }
                curSum.clear();  }
        } for (int i = 0; i < maxSum.size(); i++) {
            sb.append(maxSum.get(i));  } return sb.toString();  } public static void main(String[] args) {
        Scanner in = new Scanner(System.in);  String str = in.nextLine();  char[] chars = str.toCharArray();  char[] newChars = new char[str.length() + 1];  for (int i = 0; i < chars.length; i++) {
            newChars[i] = chars[i];  } int n = newChars.length;  newChars[n - 1] = '#';  System.out.println(MaxSubArray(newChars, n));  }
}
发表于 2018-09-03 15:00:31 回复(0)
具体思想就是遍历去找数字,这个时间是标准O(n)的,关键在i=j这句, 遍历过的不用再遍历一次,因为比之前短的就不可能成为答案。往末尾加“a“是懒得边界判断了,加“a”很方便。
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine().trim()+"a";
        char []strs = line.toCharArray();
        int tmpl = 0;
        int tmpi = 0;
        for(int i = 0; i< strs.length; i++){
            if(Character.isDigit(strs[i])){
                for(int j =i+1; j< strs.length; j++){
                    if (!Character.isDigit(strs[j])) {
                        if(j-i>tmpl){
                            tmpl = j-i;
                            tmpi = i;
                        }
                        i = j;
                        break;
                    }
                }
            }
        }
        System.out.println(line.substring(tmpi, tmpi+tmpl));
    }
}

发表于 2018-09-01 15:35:58 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()){
            String s = sc.nextLine();
            char[] arr = s.toCharArray();
            StringBuffer sb = new StringBuffer();
            String result = "";
            for (int i = 0; i < s.length() ; i++) {
                if(arr[i]>='0' && arr[i]<='9'){
                    sb.append(arr[i]);
                }else{
                    sb.setLength(0);
                }
                if(sb.length() > result.length()){
                    result = sb.toString();
                }
            }
            System.out.println(result);
        }
    }
}

发表于 2018-03-14 10:01:23 回复(0)

//暴力破解,把数组里面所有的数字串和它的长度存下来,然后输出最长的一个。

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

using namespace std;

struct number_str

{

    string math;

    int length;

};

bool comp(number_str A,number_str B)

{

    return A.length>B.length;

}

int main(int argc, const char * argv[]) {

    string A;

    cin>>A;

    vector<number_str> numbers;

    number_str temp;

    for(int i=0;i<A.length();i++)

    {

        if(A[i]<='9'&&A[i]>='0')

        {

            for(int j=i+1;j<=A.length();j++)

            {

                if(A[j]>'9'||A[j]<'0'||j==(A.length()))

                {

                    temp.math=A.substr(i,j-i);

                    temp.length=int(temp.math.length());

                    numbers.push_back(temp);

                    i=j;

                    break;

                }

            }

        }

    }

    sort(numbers.begin(), numbers.end(), comp);

    cout<<numbers[0].math<<endl;

    return 0;

}


发表于 2018-01-30 00:06:16 回复(0)
根据输入的string字符串初始化对应的int型数组,比如输入为abcd56789ww,则
对应的int数组为00001234500,找出int数组的最大值并记录位置,根据这个位置
和最大值输出最长数字串。

#include <iostream>
#include <string>
using namespace std;

int main() {  string str;  int A[255];  int i = 1;  int locat = 0, max = 0;  cin >> str;  int N = str.size();  if (str[0] >= '0' && str[0] <= '9')  A[0] = 1;  else  A[0] = 0;  while (i < N) {  if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {  A[i] = 0;  i++;  }  if (str[i] >= '0' && str[i] <= '9') {  A[i] = A[i-1] + 1;  i++;  }  }  for (int i = 0; i < N; i++) {  if (A[i] > max) {  max = A[i];  locat = i;  }  }  for (int i = (locat - max + 1); i <= locat; i++) {  cout << str[i];  }  return 0;
} 

编辑于 2018-01-29 18:43:57 回复(0)
#include <iostream>

using namespace std;

int main()
{     string s,t;     int Max = 0, cnt = 0;     cin>>s;     for(int i=0;i<s.length();i++)      {         if(s[i]>='0' && s[i]<='9')         {             cnt++;             if(Max < cnt)             {                 Max = cnt;                 t = s.substr(i-Max+1, Max);             }         }else             cnt = 0;     }     cout<<t<<endl;     return 0;
}

发表于 2018-01-14 01:12:04 回复(0)