leetcode ListNode便捷工具类
- 描述
- 工具类
- demo代码
描述
刷
leetcode
的时候,链表之类的给的都是[[1,2,3][2,3]]
这种格式的,对本地debug
找bug
不太友好,所以自己封装了一个。
工具类
@Slf4jclass ListNode {int val;ListNode next;ListNode() {}ListNode(int val) { this.val = val; }protected static ListNode preLink(int val, ListNode pre) {ListNode now = new ListNode(val);pre.next = now;return now;}protected static ListNode buildListedList(Integer[] params){if (Objects.isNull(params) || params.length == 0){return null;}ListNode root = new ListNode(params[0]);ListNode pos = root;for (int i=1; i<params.length; i++){pos = preLink(params[i], pos);}return root;}protected static ListNode buildListedList(String s){if (StringUtils.isEmpty(s)){return null;}String[] items = s.split(CommonConstants.COMMA);Integer[] params = new Integer[items.length];for (int i=0; i< items.length; i++){params[i] = Integer.parseInt(items[i]);}return buildListedList(params);}/*** 切分正则表达式 [[1,4,5],[1,3,4],[2,6]]*/private static final Pattern pattern= Pattern.compile("([0-9,]{2,})");protected static ListNode[] buildArray(String s){List<ListNode> list = new ArrayList<>();Matcher matcher = pattern.matcher(s);while (matcher.find()){list.add(buildListedList(matcher.group()));}return list.toArray(new ListNode[0]);}public static void main(String[] args) {String s = "[[1,4,5],[1,3,4],[2,6]]";
// String s = "[1,4,5]";Matcher matcher = pattern.matcher(s);while (matcher.find()){System.out.println(matcher.group());}}protected static String printPath(ListNode root){if (Objects.isNull(root)){return "";}StringBuilder builder = new StringBuilder();ListNode pos = root;while (pos != null){builder.append(pos.val).append(" => ");pos = pos.next;}builder.delete(builder.length()-4, builder.length());log.debug(builder.toString());return builder.toString();}protected static boolean checkOrder(ListNode root, boolean ascend){if (ascend){int pre = Integer.MIN_VALUE;while (root != null){if (pre > root.val){return false;}pre = root.val;root = root.next;}return true;}int pre = Integer.MAX_VALUE;while (root != null){if (pre < root.val){return false;}pre = root.val;root = root.next;}return true;}}
demo代码
github代码地址