[LeetCode]306. Additive Number

    xiaoxiao2021-03-25  55

    https://leetcode.com/problems/additive-number/?tab=Description

    给一个字符串,判断是否成立

    dfs + Long

    public class Solution { public boolean isAdditiveNumber(String num) { for (int i = 2; i <= num.length(); i++) { for (int j = 1; j < i; j++) { if (dfs(num.substring(i), num.substring(0, j), num.substring(j, i))) { return true; } } } return false; } private boolean dfs(String num, String s1, String s2) { if ((s1.charAt(0) == '0' && s1.length() > 1) || (s2.charAt(0) == '0' && s2.length() > 1)) { return false; } String res = (Long.parseLong(s1) + Long.parseLong(s2)) + ""; if (num.equals(res)) { return true; } if (res.length() > num.length() || !res.equals(num.substring(0, res.length()))) { return false; } return dfs(num.substring(res.length()), s2, res); } }

    转载请注明原文地址: https://ju.6miu.com/read-34347.html

    最新回复(0)