每日OJ_牛客_OR59字符串中找出连续最长的数字串_双指针_C++_Java
目录
牛客_OR59字符串中找出连续最长的数字串
题目解析
C++代码1
C++代码2
C++代码3
Java代码
牛客_OR59字符串中找出连续最长的数字串
字符串中找出连续最长的数字串_牛客题霸_牛客网
题目解析
双指针: 遍历整个字符串,遇到数字的时候,用双指针找出这段连续的数字子串,根据此时的长度更新起始位置和长度。
C++代码1
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cin >> s;
int begin = -1, len = 0;
for(int i = 0; i < s.size(); i++)
{
if(s[i] >= '0' && s[i] <= '9')
{
int j = i;
while(j < s.size() && s[j] >= '0' && s[j] <= '9')
{
j++;
}
if(j - i > len)
{
begin = i;
len = j - i;
}
i = j;
}
}
if(begin == -1)
{
cout << "" << endl;
}
else
{
cout << s.substr(begin, len) << endl;
}
return 0;
}
C++代码2
#include <climits>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
int sz = str.size();
int maxLen = 0;
int begin = 0, end = 0;
for(int left = 0, right = 0; left < sz && right < sz;)
{
while(left < sz && (str[left] > '9' || str[left] < '0')) // 是字母就循环
{ // 或的两个没加括号直接数组越界。。。。
++left; // 找数字区间的左边
}
right = left;
while(right < sz && str[right] >= '0' && str[right] <= '9') // 是数字就循环
{
++right; // 找数字区间的右边
}
int len = right - left;
// cout << "len : " << len << " " << left << " " << right << " sz " << sz << endl;
if(len > maxLen && left < sz && right <= sz)
{
// string tmp(str.begin() + left, str.begin() + right);
// cout << tmp << endl;
// cout << left << " " << right << " sz " << sz << endl;
end = right;
begin = left;
maxLen = len;
}
left = right;
}
string ret(str.begin() + begin, str.begin() + end);
cout << ret << endl;
return 0;
}
C++代码3
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
string str, ret = "", tmp = "";
cin >> str;
int n = str.size();
for(int i = 0; i <= n; i++)
{
if(isdigit(str[i]))
{
tmp += str[i]; // 进窗口
}
else
{
if(tmp.size() > ret.size())
{
ret = tmp;
}
else
{
tmp = "";
}
}
}
cout << ret;
return 0;
}
Java代码
import java.util.Scanner;
import java.io.*;
public class Main
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] s = br.readLine().toCharArray();
int begin = 0, len = 0;
for(int i = 0; i < s.length; i++)
{
if(s[i] >= '0' && s[i] <= '9')
{
int j = i;
while(j < s.length && s[j] >= '0' && s[j] <= '9')
{
j++;
}
if(j - i > len)
{
begin = i;
len = j - i;
}
i = j;
}
}
for(int i = begin; i < begin + len; i++)
{
System.out.print(s[i]);
}
}
}