# Java solution with regular expression

• I sketched out a three-state DFA over the sequence signs, then wrote a regular expression replacement to drop the self-loops. It's not competitive runtime-wise, but might be an interesting novelty.

import java.util.regex.Pattern;

public class Solution {

static final Pattern SELF_LOOPS_PATTERN = Pattern.compile(
"0+|(-)[0\\-]+|(\\+)[+0]+"
);

public int wiggleMaxLength(int[] nums) {
if (nums.length == 0)
return 0;
if (nums.length == 1)
return 1;

StringBuilder signs = new StringBuilder(nums.length-1);

for (int t = 0; t < nums.length - 1; ++t) {
int sign = Integer.signum(nums[t+1] - nums[t]);
switch (sign) {
case  0: signs.append("0"); break;
case  1: signs.append("+"); break;
case -1: signs.append("-"); break;
}
}

return SELF_LOOPS_PATTERN.matcher(signs).replaceAll("\$1\$2").length() + 1;
}
}

• I like it. Wouldn't use + and -, though, because of their special meaning, and I'd shorten some other things as well:

import java.util.regex.Pattern;

public class Solution {

static final Pattern SELF_LOOPS_PATTERN = Pattern.compile(
"=+|(<)[<=]+|(>)[>=]+"
);

public int wiggleMaxLength(int[] nums) {
if (nums.length <= 1)
return nums.length;

StringBuilder signs = new StringBuilder(nums.length-1);

for (int t = 1; t < nums.length; ++t) {
int sign = Integer.signum(nums[t] - nums[t-1]);
signs.append("<=>".charAt(sign+1));
}

return SELF_LOOPS_PATTERN.matcher(signs).replaceAll("\$1\$2").length() + 1;
}
}

• It's so interesting, thanks for your post!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.