숫자만 있는 문자열이 있다고 가정하고 가능한 모든 유효한 IP 주소 조합을 구성하여 이를 복원해야 합니다. 유효한 IP 주소는 단일 마침표 기호로 구분된 정확히 4개의 정수(각 정수의 범위는 0~255)로 구성되어 있습니다.
따라서 입력이 ip ="25525511136"과 같으면 출력은 ["254.25.40.123", "254.254.0.123"]
가 됩니다.이 문제를 해결하기 위해 다음 단계를 따릅니다. −
- convertToNum() 함수를 정의하면 s, 시작, 종료,
- num :=0
- 초기화 i :=시작의 경우, i <=끝일 때 업데이트(i 1만큼 증가), 수행 -
- num :=(num * 10) + (s[i] - '0'의 ASCII)
- 숫자> 255이면 -
- 10000 반환
- 반환 번호
- addDots() 함수를 정의하면 위치가 지정됩니다.
- res :=빈 문자열
- x :=0, posIndex :=0
- 초기화 i의 경우:=0, i <위치 크기일 때 업데이트(i 1만큼 증가), 수행 -
- num :=위치[i]
- 하나의 문자열 str1 생성
- temp :=문자열로 된 숫자
- res :=res + temp
- i <위치의 크기이면 −
- res :=res 연결 "."
- 반환 결과
- solve() 함수를 정의하면 s, 하나의 문자열 배열 결과, 배열 위치, dotCount, 3으로 초기화, startIndex, 0으로 초기화
- dotCount가 0이 아니고 ((size of s - 1) - startIndex + 1) 1이 아니면 -
- temp :=convertToNum(s, startIndex, s의 크기)
- temp>
=0이고 temp <=255이면 -
- 위치 끝에 온도 삽입
- res :=addDots(위치)
- res의 크기가 s의 크기와 같으면 -
- 결과 끝에 res 삽입
- 반환
- 초기화 i :=startIndex의 경우, i <크기가 s인 경우 업데이트(i를 1만큼 증가), 수행 -
- temp :=convertToNum(s, startIndex, i)
- temp>
=0이고 temp <=255이면 -
- 위치 끝에 온도 삽입
- 해결(s, 결과, 위치, dotCount - 1, i + 1)
- 위치에서 마지막 요소 삭제
- 하나의 함수 정의 genIp 이것은 문자열 s를 취합니다
- 배열 결과 정의
- 배열 위치 정의
- 해결(, 결과, 위치)
- 반환 결과
- 메인 메소드 호출에서 genIp(A)
예시(C++)
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
typedef long long int lli;
class Solution {
public:
lli convertToNum(string s,int start, int end){
lli num = 0;
for (int i = start; i <= end; i++) {
num = (num * 10) + (s[i] - '0');
if (num > 255)
return 10000;
}
return num;
}
string addDots(vector <int> positions){
string res = "";
int x = 0;
int posIndex = 0;
for (int i = 0; i < positions.size(); i++) {
int num = positions[i];
ostringstream str1;
str1 << num;
string temp = str1.str();
res += temp;
if (i < positions.size() - 1)
res += ".";
}
return res;
}
void solve(string s, vector <string> &result,vector <int> positions, int dotCount = 3, int startIndex = 0){
if (!dotCount && ((s.size() - 1) - startIndex + 1) >= 1) {
int temp = convertToNum(s, startIndex, s.size() - 1);
if (temp >= 0 && temp <= 255) {
positions.push_back(temp);
string res = addDots(positions);
if (res.size() - 3 == s.size()) {
result.push_back(res);
}
}
return;
}
for (int i = startIndex; i < s.size(); i++) {
int temp = convertToNum(s, startIndex, i);
if (temp >= 0 && temp <= 255) {
positions.push_back(temp);
solve(s, result, positions, dotCount - 1, i + 1);
positions.pop_back();
}
}
}
vector<string> genIp(string s){
vector<string> result;
vector<int> position;
solve(s, result, position);
return result;
}
vector<string> get_ip(string A) {
return genIp(A);
}};
main(){
Solution ob;
string ip = "25525511136";
print_vector(ob.get_ip(ip));
} 입력
25525511136
출력
[255.255.11.136, 255.255.111.36, ]