首页 > 试题广场 > 在字符串中找出连续最长的数字串
[编程题]在字符串中找出连续最长的数字串

样例输出

输出123058789,函数返回值9

输出54761,函数返回值5

 

接口说明

函数原型:

   unsignedint Continumax(char** pOutputstr,  char* intputstr)

输入参数:
   char* intputstr  输入字符串;

输出参数:
   char** pOutputstr: 连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串;如果输入字符串是空,也应该返回空字符串;  

返回值:
  连续最长的数字串的长度

 

 

 

 


输入描述:

输入一个字符串。



输出描述:

输出字符串中最长的数字字符串和它的长度。如果有相同长度的串,则要一块儿输出,但是长度还是一串的长度

示例1

输入

abcd12345ed125ss123058789

输出

123058789,9

138个回答

添加回答
将不是数字的字符全部变成‘a’,再将字符串用a来分割称数组,长度最大的数组的长度即为所求的长度,
import java.util.*;
public class Main{
	public static void main(String[] args) {

		Scanner scan=new Scanner(System.in);
		while(scan.hasNext())
		{
			String str1="";
			String str=scan.nextLine();
			for(char ch:str.toCharArray()){
				//将不是数字的字符全部变成a
				if(ch>='0' && ch<='9'){
					str1+=ch;
				}else{
					str1+="a";
				}
			}
			//按a分割
			String[] strs=str1.split("a");
			int max=0;//记录最长的连续数字串的长度
			for(int i=0;i<strs.length;i++){
				max=strs[i].length()>max?strs[i].length():max;
			}
			for(int i=0;i<strs.length;i++){
				if(strs[i].length()==max)
					System.out.print(strs[i]);
			}
			System.out.println(","+max);
		}
	}
}

发表于 2016-08-25 10:59:21 回复(6)
#include <iostream>
#include <string>
using namespace std;
int main()
{ 	
    string str;
    while( cin>>str )
    {
        int i;
        int max = 0;
        string ss;
        string out;
        for(i = 0; i < str.size(); i++)
        {
            if(str[i] >= '0' &&str[i] <= '9')
            {
                ss += str[i];
                while(str[i+1] >= '0' &&str[i+1] <= '9')
                {
                    i++;
                    ss += str[i];
                }
                if(ss.size() > max)
           		{
                	max = ss.size();
                    out = ss;               	
            	}
                else if(ss.size() == max)
                    out += ss;
            } 
            ss.clear();            
        }
        cout<<out<<','<<max<<endl;        
    }
    return 0;
}

发表于 2017-03-16 11:05:47 回复(7)

python solution

while True:
    try:
        a = input()
        maxLen, maxStrs, curLen, curStr = 0, [], 0, ""
        for i, v in enumerate(a):
            if v.isnumeric():
                curLen += 1
                curStr += v
                if curLen > maxLen:
                    maxLen = curLen
                    maxStrs = [curStr]
                elif curLen == maxLen:
                    maxStrs.append(curStr)
            else:
                curLen = 0
                curStr = ""
        print("".join(maxStrs) + "," + str(maxLen))
    except:
        break

也可以使用正则表达式来直接匹配数字。

编辑于 2017-10-17 14:44:22 回复(0)
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); while (in.hasNext())
        {
            String str=in.nextLine();
            String[] arr=str.split("\\D+");
            String sss=arr[0]; int max=arr[0].length(); for(int i=1;i<arr.length;i++)
            { if(arr[i].length()>max)
                {
                    sss=arr[i];
                    max=arr[i].length();
                } else if(arr[i].length()==max)
                {
                    sss+=arr[i];
                }
            }
            System.out.println(sss+","+max);
        }
    }
}

发表于 2016-10-29 13:08:23 回复(5)
import java.util.Scanner;

public class Main{//子串系列,简单动态规划,dp[i]代表当前i的最长数字长度
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			String str = in.nextLine();
			int len = str.length();
			int max = 0;
			int dp[] = new int[len];
			int flag =0;
			//动态规划边界
			if (str.charAt(0)>='0'&&str.charAt(0)<='9') {
				
				dp[0]=1;
			}
			for (int i = 1; i < len; i++) {
				if (str.charAt(i)>='0'&&str.charAt(i)<='9') {
					dp[i]=dp[i-1]+1;
				}else {
					dp[i]=0;
				}
			}
			for (int i = 0; i < dp.length; i++) {
				if (dp[i]>max) {
					max = dp[i];
					flag = i;
				}
			}
			String temp = "";
			for (int i = 0; i < dp.length; i++) {
				if (dp[i]==max) {
					temp+=str.substring(i-max+1,i+1);
				}
			}
			//System.out.println(str.substring(flag-max+1,flag+1)+","+max);
			System.out.println(temp+","+max);
		}
	}
}

编辑于 2016-08-19 20:00:34 回复(1)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){
    string str;
    while(cin>>str){
        vector<string> array;
        string temp;
        for(int i=0;i<=str.length();i++){
            if(str[i]>='0'&&str[i]<='9')
                temp+=str[i];
            else{
                if(temp.length()!=0){
                    array.push_back(temp);
                }
                temp.clear();
            }
        }
        int max=0,length;
        for(int i=0;i<array.size();i++){
        	if(max<(array[i]).length()){
        		max=(array[i]).length();
        		length=max;
			}
		}
		for(int i=0;i<array.size();i++){
        	if((array[i]).length()==max)
        		cout<<array[i];
		}
        
		cout<<','<<length<<endl;  
    }
    return 0;
}

发表于 2016-08-02 15:53:50 回复(4)
来个纯C语言敲的,累死了。先找出最长数字串的长度,然后再判断遍历到的数字串是不是最长的。 如果是最长的,记录下这串数字起始的位置,最后一起打印出来。
#include<stdio.h>
#include<string.h>
int main()
{
	char str[1000];
	int b[1000]={0};
	int i,j,k,len,cnt=0,cnt0=0,max=0;
	while(scanf("%s",&str)!=EOF)
	{
		cnt=0,cnt0=0,max=0,j=0;
		len=strlen(str);
		for(i=0;i<len;)
		{
			if((str[i]>='0')&&(str[i]<='9'))
			{
				while((str[i]>='0')&&(str[i]<='9'))
				{
					cnt++;
					i++;
				}
				if(cnt>max)
					max=cnt;			
			}
			else
			{
				cnt=0;
				i++;
			}
		}
		for(i=0;i<len;)
		{
			if((str[i]>='0')&&(str[i]<='9'))
			{
				while((str[i]>='0')&&(str[i]<='9'))
				{
					cnt0++;
					i++;
				}
				if(cnt0==max)
					b[j++]=i-max;	
			}
			else
			{
				cnt0=0;
				i++;
			}				
		}
		for(k=0;k<j;k++)
			for(i=b[k];i<b[k]+max;i++)
				printf("%c",str[i]);				
        printf(",");
		printf("%d\n",max);
	}
	return 0;
}


编辑于 2017-09-11 09:44:45 回复(0)
遍历字符串,判断是否为数字,如果是数字,len加1,并取出数字字符串,放到vector里面,当出现非数字的时候,如果发现len大于当前的最大长度的时候,清空vector,把新的字符串放进去,同时跟新找到的最大数字子串的长度。如果发现len与最大子串长度相等,就直接放到vector里面。
#include<string>
#include<cctype>
#include<iostream>
#include<vector>
using namespace std;
int main()
{
//freopen("maxstr.txt","r",stdin);
string str;
while(cin>>str)
{
int maxlen=0;
int len=0;
string stmp;
vector<string> vec;
for(int i=0;i<str.size();i++)
{
if(isdigit(str[i]))
{
++len;
}
else
{
if(len==0)
continue;
if(maxlen<=len)
{
if(maxlen<len)
{
vec.clear();
maxlen=len;
//len=0;
}
stmp=str.substr(i-maxlen,maxlen);
vec.push_back(stmp);
}
len=0;
}
}
if(maxlen == len)
{
stmp=str.substr(str.size()-maxlen,maxlen);
vec.push_back(stmp);
}
if(maxlen<len)
{
vec.clear();
maxlen=len;
stmp=str.substr(str.size()-maxlen,maxlen);
vec.push_back(stmp);
}
for(int i=0;i<vec.size();i++)
cout<<vec[i];
            cout<<","<<maxlen<<endl;
}
return 0;
}
发表于 2017-07-04 17:32:08 回复(0)
import re
try:
    while 1:
        a = re.findall('\d+', raw_input())
        n = len(max(a, key=len))
        print ''.join(filter(lambda x:len(x) == n, a)) + ',' + str(n)
except:
    pass

发表于 2017-01-05 20:01:22 回复(0)
第一步: 将所有非数字的字符全部转化为空格
第二步: 使用stringstream将字符串分割成数字组成的字符串, 然后比较长度即可
#include <iostream>
#include <string>
#include <sstream>   // sstringstream

using namespace std;

int main(){
    string str;
    while(cin >> str){
        for(auto &c : str){
            if(!isdigit(c))
                c = ' ';
        }

        stringstream ss(str);
        unsigned int max_sz = 0;
        string s, o;
        while(ss >> s){
            if(max_sz < s.size()){
                max_sz = s.size();
                o = s;
            }else if(max_sz == s.size())
                o += s;
        }

        if(max_sz != 0)
            cout << o << "," << max_sz << endl;
    }
    return 0;
}

发表于 2017-08-10 21:29:19 回复(2)
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

unsigned int Continumax(char** pOutputStr, char* inputstr)
{
	if (inputstr == NULL)
		return 0;
	int sz = strlen(inputstr);
	*pOutputStr = new char[sz + 1];

	int maxLen = 0;
	int start = 0, maxStart = 0, maxEnd = 0;
	for (int i = 0; i <= sz; ++i)
	{
		int cnt = 0;
		start = i;
		while (i < sz && inputstr[i] >= '0' && inputstr[i] <= '9')
		{
			++i;
			++cnt;
		}// while        
		if (cnt >= maxLen)
		{
			maxLen = cnt;
			maxStart = start;
			maxEnd = i;
		}// if
	}// for

	int outputIdx = 0;
	for (int i = maxStart; i < maxEnd; ++i)
		(*pOutputStr)[outputIdx++] = inputstr[i];
	(*pOutputStr)[outputIdx] = '\0';

	return maxLen;
}

int main()
{
	char* pOutput = NULL;
	char** ppOutput = &pOutput;
	char* pInput = new char[100];

	while (scanf("%s", pInput))
	{
		int len = Continumax(ppOutput, pInput);
		printf("%s,%d", *ppOutput, len);
	}

	char ch;
	getchar();
	return 0;
}
在VS2015上可以运行,为什么这个上面不行呢。。。
编辑于 2017-08-10 16:20:59 回复(0)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

bool compare(string a,string b){
    return a.size()>b.size();
}
int main(){
    string input;
    while(cin>>input){
        vector<string> res;
        for(int i=0;i<input.size();){
            while(input[i]<'0'||input[i]>'9')
                i++;
            int j=i;
            while(input[j]>='0'&&input[j]<='9')
                j++;
            string temp=input.substr(i,j-i);
            res.push_back(temp);
            i=j;
        }
        stable_sort(res.begin(),res.end(),compare);
        for(int i=0;i<res.size();++i){
            if(res[i].size()!=res[0].size())
                break;
            cout<<res[i];
        }
        cout<<','<<res[0].size()<<endl;
    }
}

发表于 2016-08-31 21:58:36 回复(0)
import java.util.*;
public class lianxu{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
            String str = scan.next();
            ArrayList<String> list = new ArrayList<String>(); 
            for(int i=0;i<str.length();i++){
                for(int j=i+1;j<str.length();j++){
                    if(str.charAt(i)>='0'&&str.charAt(i)<='9'){
                        if(
                      str.charAt(j)>='0'&&str.charAt(j)<='9'){
                        	if(j==str.length()-1){
                        		list.add(str.substring(i, str.length()));
                        	}
                    } else{
						list.add(str.substring(i,j));
                            break;
                        }
                    }
                    else{
                       continue;
                    }
                   
                }
            }
           int max = 0;
           for(int i=0;i<list.size();i++) {
        	   if(list.get(i).length()>max){
        		   max=list.get(i).length();
        	   }
           }
           StringBuilder sb = new StringBuilder();
            for(int i=0;i<list.size();i++){
            	if(list.get(i).length()==max){
            		//System.out.println(list.get(i)+","+max);
            		sb.append(list.get(i));
            	}
            }
            System.out.println(sb+","+max);
        }
        }
    }
}
这题太坑了,字符串长度一样的竟然同时输出
发表于 2016-06-17 11:07:07 回复(1)
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
void print(string str) {
	string res, tmp;
	int len = 0;
	stringstream ss;
	ss << str;
	while (getline(ss, tmp, ' '))
		if (tmp[0] != ' ' && tmp.size() == len) res += tmp;
		else if (tmp[0] != ' ' && tmp.size() > len) {
			res = tmp;
			len = tmp.size();
		}
	cout << res << "," << len << endl;
}
int main() {
	string str;
	while (getline(cin, str)) {
		for (int i = 0; i < str.size();i++) if (!isdigit(str[i])) str[i] = ' ';
		print(str);
	}
}

发表于 2017-03-20 16:19:22 回复(0)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{     string str;     while (cin >> str)     {         int len = str.size();         int i = 0;         int s = 0, sm = 1;         vector<string> L;         while (i < len)         {             if (str[i] <= '9'&&str[i] >= '0')             {                 s = 1;                 int j = i + 1;                 while (str[j] <= '9'&&str[j] >= '0'&&j < len)                 {                     s++;                     j++;                 }                 if (s >= sm)                 {                     string l = str.substr(i, s);                     L.push_back(l);                     sm = s;                 }                 i = j;             }             i++;         }         int k = L.size();         int c = L[k - 1].size();         for (int k = 0; k < L.size(); k++)         {             if (L[k].size() == c)                 cout << L[k];         }         cout << ","<<sm<<endl;     }     return 0;
}

发表于 2019-04-03 21:46:30 回复(0)
你们的都太复杂了,上代码,相对好理解。
#include<bits/stdc++.h>
using namespace std;
int main(){
    string k;
    while(cin>>k){
        int max=0;
        int temp=0;
        int flag=0;
        vector<int> z;
        for(int i=0;i<k.size();++i){
            if(k[i]>='0'&&k[i]<='9'){
                temp++;
            }else{
                temp=0;
            }
            if(temp==max){
                z.push_back(i);
            }
            if(temp>max){
                flag=i;
                max=temp;
                z.clear();
                z.push_back(flag);
            }
        }
        for(int j=0;j<z.size();++j){
            for(int i=z[j]-max+1;i<=z[j];++i){
                cout<<k[i];
            }
        }
        cout<<","<<max<<endl;
    }
    return 0;
}
发表于 2019-03-14 11:02:29 回复(0)
import java.util.*;
import java.util.regex.*;
public class Main {
    public static void main(String[] args){
            Scanner sc = new Scanner(System.in);
            while(sc.hasNext()){
                String line = sc.nextLine();
                Pattern p = Pattern.compile("\\d+");
                Matcher m = p.matcher(line);
                List<String> ss = new ArrayList<String>();
                while(m.find()) {
                    ss.add(m.group());
                }
                int cnt = 0;
                String result = "";
                List<String> sres = new ArrayList<String>();
                for(String s : ss) {
                    if(s.length() > cnt) {
                        cnt = s.length();
                        sres = new ArrayList<String>();
                        sres.add(s);
                    } else if(s.length() == cnt) {
                        sres.add(s);
                    }
                }
                for(String s : sres) {
                    System.out.print(s);
                }
                System.out.println(","+cnt);
            }
    }
}

发表于 2018-10-09 13:41:55 回复(0)
利用split()函数正则表达式来完成这道题。
代码简洁,清晰
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()){
            String str= sc.nextLine();
            String[] strs = str.split("[^0-9]");
            int max = 0;
            for(int i = 0;i<strs.length;i++){
                if(max<strs[i].length())
                    max = strs[i].length();
            }
            String result = "";
            for(int i =0;i<strs.length;i++){
                if(strs[i].length()==max)
                    result+=strs[i];
            }
            System.out.println(result+","+max);
        }
    }
}

发表于 2018-08-10 22:16:19 回复(0)
#include <bits/stdc++.h>

using namespace std;




int main()
{
    string str;

    while (getline(cin, str))
    {
        string res;
        int max1 = 0;
        int cnt = 0;
        for (int i = 0; i<str.size(); i++)
        {
            if (str[i]>='0' && str[i]<='9')
            {
                cnt = 0;
                while (str[i]>='0' && str[i]<='9')
                {
                    cnt++;
                    i++;
                }
                max1 = max(max1, cnt);
            }
        }
        for (int i = 0; i<str.size(); i++)
        {
            cnt = 0;
            if (str[i]>='0' && str[i]<='9')
            {
                cnt = 0;
                while (str[i]>='0' && str[i]<='9')
                {
                    res.push_back(str[i]);
                    cnt++;
                    i++;
                }
                if (cnt == max1)
                {
                    for (int j = 0; j < res.size(); j++)
                    {
                        cout << res[j];
                    }
                }
                else res.clear();
            }
        }
        cout << "," << max1 << endl;

    }
    system("pause");
    return 0;

}  

发表于 2018-08-05 23:14:14 回复(0)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
    string s;
    while(cin>>s){
        vector<string> v;
        string str;
        for(int i=0;i<=s.length();i++){
            if(s[i]>='0' && s[i]<='9') str+=s[i];
            else{
                if(v.empty())
                    v.push_back(str);
                else if(str.length()>v[0].length()){
                    v.clear();
                    v.push_back(str);
                }else if(str.length()==v[0].length())
                    v.push_back(str);
                str="";
            }
        }
        vector<string>::iterator it=v.begin();
        for(;it!=v.end();it++) cout<<*it;
        cout<<','<<v[0].length()<<endl;
    }
    return 0;
}

发表于 2018-07-26 21:23:00 回复(0)

扫一扫,把题目装进口袋

牛客网,程序员必备求职神器

扫描二维码,进入QQ群

扫描二维码,关注牛客网公众号