题解 | #数字字符串转化成IP地址#
数字字符串转化成IP地址
https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串一维数组 */ pub fn restoreIpAddresses(&self, s: String) -> Vec<String> { let mut x = Data::new(); let res = x.restore_ip_addresses(s); res } } #[derive(Debug)] struct Data{ stack: Vec<String>, res: Vec<String> } impl Data { fn new() -> Self { Data{ stack: Vec::new(), res: Vec::new() } } pub fn restore_ip_addresses(&mut self, s: String) -> Vec<String> { self.dfs(s); self.res.clone() } fn dfs(&mut self, cur_str: String){ if self.stack.len() < 3 { for i in 1..4{ if cur_str.len() < i { continue; } match cur_str[0..i].parse::<u8>() { Ok(parsed_number) => { if parsed_number.to_string().len() == cur_str[0..i].len() { self.stack.push(cur_str[0..i].to_string()); self.dfs(cur_str[i..].to_string()); self.stack.pop(); } } Err(_) => {} } } }else { match cur_str.parse::<u8>() { Ok(parsed_number) => { if parsed_number.to_string().len() == cur_str.len() { self.stack.push(cur_str.to_string()); self.res.push(Self::fmt(&self.stack).unwrap()); self.stack.pop(); } } Err(_) => {} } } } fn fmt(stack: & Vec<String>) -> Option<String>{ Some(stack.iter().fold(String::new(), |acc, s| { if acc.is_empty() { s.clone() } else { acc + "." + s } })) } }
我就是传说中的根据编译器提示写代码的垃圾,Rust解法很恶心,可能是我太菜,我在本地可以运行的代码在在线上运行不了,报错内容是:expected struct std::num::ParseIntError
, found struct std::io::Error;
无奈改了代码,随后提示我restoreIpAddresses函数传的self是不可变引用,无奈又包装了一下,最终的代码长这个样子,我知道很丑,大佬不要喷我,思路非常简单,无脑回溯,不用动脑子做题真的很舒服。