문자열이 주어집니다. 문자열에는 숫자만 포함됩니다. 우리의 임무는 가능한 모든 유효한 IP 주소 조합을 확인하는 것입니다.
여기서 먼저 문자열의 길이를 확인한 다음 "."로 분할합니다. 그런 다음 "."의 다른 조합을 확인합니다.
예
Input : "255011123222" It's not a valid IP address. Input : 255011345890 Valid IP address is 255.011.123.222
알고리즘
Step 1: First check the length of the string. Step 2: Split the string by ".". We will place 3 dots in the given string. W, X, Y, and Z are numbers from 0-255 the numbers cannot be 0 prefixed unless they are 0. Step 3: Generating different combinations. Step 4: Check for the validity of combination.
예시 코드
# Python code to check valid possible IP # Function checks wheather IP digits # are valid or not. def ipvalid(ip): # Spliting by "." ip = ip.split(".") # Checking for the corner cases for i in ip: if len(i) > 3 or int(i) < 0 or int(i) > 255: return False if len(i) > 1 and int(i) == 0: return False if len(i) > 1 and int(i) != 0 and i[0] == '0': return False return True # Function converts string to IP address def ipconvert(A): con = len(A) # Check for string size if con > 12: return [] newip = A l = [] # Generating different combinations. for i in range(1, con - 2): for j in range(i + 1, con - 1): for k in range(j + 1, con): newip = newip[:k] + "." + newip[k:] newip = newip[:j] + "." + newip[j:] newip = newip[:i] + "." + newip[i:] # Check for the validity of combination if ipvalid(newip): l.append(newip) newip = A return l # Driver code A = input("Enter IP address") print(ipconvert(A))
출력
Enter IP address25525522134 ['255.255.22.134', '255.255.221.34']