題解 | 數(shù)字字符串轉(zhuǎn)化成IP地址
數(shù)字字符串轉(zhuǎn)化成IP地址
http://fangfengwang8.cn/practice/ce73540d47374dbe85b3125f57727e1e
/** * 代碼中的類名、方法名、參數(shù)名已經(jīng)指定,請勿修改,直接返回方法規(guī)定的值即可 * * * @param s string字符串 * @return string字符串一維數(shù)組 */ function restoreIpAddresses( s ) { //檢驗合法性 const result = [] function is_valid(str){ if (str.length >1 && str[0] === '0') { return false } if (parseInt(str) > 255) { return false } return true } function backtrack( path , start ) { if (path.length === 4 && start === s.length) { //此時合法 加入結(jié)果中 result.push(path.join('.')) } if (path.length === 4) { return } for(let i =1;i<=3;i++) { if (start + i>s.length) { break } const strChild = s.substring(start,start+i) if (is_valid(strChild)) { backtrack([...path,strChild], start+i ) } } } backtrack([],0) return result } module.exports = { restoreIpAddresses : restoreIpAddresses };