1写一个算法判断某个字符串是不是一个合法的IP地址。
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
bool IsIpaddr(char *ipaddr)
{
if(ipaddr == NULL)
return false;
char *token;
const char *delim = ".";
token = strtok(ipaddr,delim);
if(!token)
{
return false;
}
while(token)
{
int temp = atoi(token);
if(temp < 0 || temp > 255)
{
return false;
}
token = strtok(NULL,delim);
}
return true;
}
int main()
{
const int length = 60;
char ipaddr[length] = "192.168.0.28";
if(IsIpaddr(ipaddr))
{
cout << "is ipaddr format" << endl;
}
else
{
cout << "is not ipaddr format" << endl;
}
return 0;
}
在Linux下,可以借助库函数inet_pton来判断是否为ipv4或者ipv6。
2给定一字符串只包含数字,请写一个算法,找出该字符串中的最长不重复子串(不重复是指子串中每一元素不同于子串中其他元素)
如: “120135435”最长不重复子串为 “201354”
#include <iostream>
#include <cassert>
#include <string>
#include <algorithm>
using namespace std;
void LongestSubstring(string& s)
{
assert(s.size() != 0);
int n = s.size();
int i, j,longest,start;
for (i = 0; i < n; ++i)
{
bool exist[10] = {false};
exist[s[i]-'0'] = true;
for (j = i + 1; j < n; ++j)
{
if (exist[s[j]-'0'] == false)
{
exist[s[j]-'0'] = true;
}
else
{
if (j - i > longest)
{
longest = j - i;
start = i;
}
break;
}
}
if ((j == n) && (j - i > longest))
{
longest = j - i;
start = i;
}
}
cout<<start<<" "<<longest<<endl;
string temp = s.substr(start,longest);
cout<<temp<<endl;
}
int main()
{
string s("120135435");
LongestSubstring(s);
return 0;
}
本文介绍了一个简单的IP地址验证算法,并提供了一种找出数字字符串中最长不重复子串的有效方法。
3730

被折叠的 条评论
为什么被折叠?



