理论上每个字符只会被使用到一次,从而保证算法的时间复杂度,满足mqtt协议的“+”、“#”通配符要求。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
public class TopicUtils {
public static void main(String[] args) { String topicRule = "aa/+/bb/+/+/cc/#"; String topic = "aa/11/bb/2222/4444/cc/5555//"; System.out.println("是否匹配:" + match(topicRule, topic));
topicRule = "+"; topic = "aa"; System.out.println("是否匹配:" + match(topicRule, topic));
topicRule = "+/#"; topic = "aa/cc/dd"; System.out.println("是否匹配:" + match(topicRule, topic));
topicRule = "/+/"; topic = "/aa/"; System.out.println("是否匹配:" + match(topicRule, topic));
topicRule = "aa/#"; topic = "aa"; System.out.println("是否匹配:" + match(topicRule, topic)); }
public static boolean match(String topicRule, String topic) { char[] topicRuleChar = topicRule.toCharArray(); char[] topicChar = topic.toCharArray(); int topicIndex = 0;
ruleSign: for (int i = 0; i < topicRuleChar.length; i++) {
char indexRuleChar = topicRuleChar[i];
if (indexRuleChar == '#' && topicRuleChar[i - 1] == '/'){ return true; }
if (topicIndex == topicChar.length){ if (i + 2 == topicRuleChar.length && topicRuleChar[i] == '/' && topicRuleChar[i + 1] == '#'){ return true; } if (indexRuleChar != '+'){ return false; } } if (topicIndex != topicChar.length && indexRuleChar == topicChar[topicIndex]){ topicIndex++; continue; }
if (indexRuleChar == '+'){ if (topicRuleChar.length == 1){ for (int j = 0; j < topicChar.length; j++) { if (topicChar[j] == '/'){ return false; } } return true; }else if (i == 0 && topicRuleChar[i + 1] == '/'){ for (int j = topicIndex; j < topicChar.length; j++) { if (topicChar[j] == '/'){ topicIndex = j; continue ruleSign; } } return false; }else if (i != 0 && topicRuleChar[i - 1] == '/'){ if (topicRuleChar.length - 1 <= i){ for (int j = topicIndex; j < topicChar.length; j++) { if (topicChar[j] == '/'){ return false; } } return true; }else if (topicRuleChar[i + 1] == '/'){ for (int j = topicIndex; j < topicChar.length; j++) { if (topicChar[j] == '/'){ topicIndex = j; continue ruleSign; } } return false; } } } return false; } if (topicIndex < topicChar.length){ return false; } return true; }
}
|