LeetCode 093 Restore IP Addresses
2015-10-26 12:46
441 查看
题目描述
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)
代码
[code] List<String> result = new ArrayList<String>(); String[] stack = new String[4]; public List<String> restoreIpAddresses(String s) { if (s == null || s.length() == 0) { return new ArrayList<String>(); } dfs(s, 0, 0); return result; } /** * * @param s * @param p * :指针 * @param pstack * :stack的下标 */ public void dfs(String s, int p, int pstack) { if (pstack == 4) { // 如果stack长度为4,且s的字符全部用上 // 则stack[0...3]存了一个结果 if (p >= s.length()) { String ip = String.join(".", stack); result.add(ip); } return; } // 获取1~3个字符 for (int i = 1; i <= 3; i++) { // 如果超过字符串长度,返回 if (p + i > s.length()) { return; } // 若选取的第一个字符是0,则停止选取 if (i > 1 && s.charAt(p) == '0') { continue; } String number = s.substring(p, p + i); // 如果number<=255,递归 if (Integer.parseInt(number) <= 255) { stack[pstack] = number; dfs(s, p + i, pstack + 1); } } }
相关文章推荐
- error 65: access violation at 0x40021000 : no 'read' permission
- 算法的力量
- html如何给登录按钮换样式
- str 函数 将小数转换为varchar类型
- Python二维码生成库qrcode安装和使用示例
- 开篇
- Android多媒体编程——图片的大小计算
- Mac下 android 模拟器/真机 host修改
- HTML基础(登录按钮如何改样式)
- ShortestPath:Silver Cow Party(POJ 3268)
- linux 下的socket 客户端开发
- 自定义progressdialog加载动画,这里还有旋转的加载条,美团,多个图片动画
- RTS与CTS的含义
- Boost.asio 一些注意事项
- messagepcak 资料
- Android Activity之 setContentView()总结
- 部分面试题
- Android DEX安全攻防战
- 散列表
- tips for configuring your .vimrc