Leetcode: Restore IP addresses

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   ar   for   div   sp   

Given a string containing only digits, restore it by returning all possible valid IP address combinations.For example:Given "25525511135",return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

NP問題。也是採用遞迴的解法。基本思路就是取出一個合法的數字,作為IP地址的一項,然後遞迴處理剩下的項。可以想象出一顆樹,每個結點有三個可能的分支(因為範圍是0-255,所以可以由一位兩位或者三位組成)。並且這裡樹的層數不會超過四層,因為IP地址由四段組成,到了之後我們就沒必要再遞迴下去,可以結束了。這裡除了上述的結束條件外,另一個就是字串讀完了。

 1 public class Solution { 2     public List<String> restoreIpAddresses(String s) { 3         ArrayList<String> res = new ArrayList<String>(); 4         if (s == null || s.length() == 0) return res; 5         helper(res, "", s, 1, 0); 6         return res; 7     } 8      9     public void helper(ArrayList<String> res, String item, String s, int level, int index) {10         if (index >= s.length()) return;11         if (level == 4) {12             String st = s.substring(index);13             if (isValid(st)) {14                 String f = String.format("%s.%s", item, st);15                 res.add(f);16             }17             return;18         }19         for (int i=1; i<4&&(index+i<=s.length()); i++) {20             String str = s.substring(index, index+i);21             if (isValid(str)) {22                 if (item.length() == 0) {23                     helper(res, str, s, level+1, index+i);24                 }25                 else {26                     String temp = String.format("%s.%s", item, str);27                     helper(res, temp, s, level+1, index+i);28                 }29             }30         }31     }32     33     public boolean isValid(String str) {34         if (str == null || str.length()>3) return false;35         if (str.charAt(0) == ‘0‘ && str.length()>1) return false;36         int num = Integer.parseInt(str);37         if (num>=0 && num<=255) {38             return true;39         }40         return false;41     }42 }

 

Leetcode: Restore IP addresses

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.