zoukankan      html  css  js  c++  java
  • DFA算法以及ios中OC实现DFA

    DFA不同于苹果手机的idfa

    DFA全称为:Deterministic Finite Automaton,即确定有穷自动机。其特征为:有一个有限状态集合和一些从一个状态通向另一个状态的边,每条边上标记有一个符号,其中一个状态是初态,某些状态是终态。但不同于不确定的有限自动机,DFA中不会有从同一状态出发的两条边标志有相同的符号。

    ios  oc 代码如下

    #import "WordFilter.h"

    #define EXIST @"isExists"

    @interface WordFilter()

    @property (nonatomic,strong) NSMutableDictionary *root;

    @property (nonatomic,assign) BOOL isFilterClose;

    @end

    @implementation WordFilter

    static WordFilter *instance;

    + (instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    instance = [[self alloc]init];
    });
    return instance;
    }

    - (void)initFilter:(NSString *)filepath{

    self.root = [NSMutableDictionary dictionary];
    char word[1024];
    FILE *fp;
    char *p;

    //打开文件
    fp = fopen([filepath UTF8String], "r");

    //按行读取内容
    while (fgets(word, sizeof(word), fp)) {
    p = word;

    while (*p != 0) {
    if (*p == ' ' || *p == ' ' || *p == ' ') {
    *p = 0;
    break;
    }
    p++;
    }

    //插入字符,构造节点
    [self insertWords:[NSString stringWithUTF8String:word]];
    }
    }

    -(void)insertWords:(NSString *)words{
    NSMutableDictionary *node = self.root;

    for (int i = 0; i < words.length; i ++) {
    NSString *word = [words substringWithRange:NSMakeRange(i, 1)];

    if (node[word] == nil) {
    node[word] = [NSMutableDictionary dictionary];
    }

    node = node[word];
    }

    //敏感词最后一个字符标识
    node[EXIST] = [NSNumber numberWithInt:1];
    }

    - (NSString *)filter:(NSString *)str{

    if (self.isFilterClose || !self.root) {
    return str;
    }

    NSMutableString *result = result = [str mutableCopy];

    for (int i = 0; i < str.length; i ++) {
    NSString *subString = [str substringFromIndex:i];
    NSMutableDictionary *node = [self.root mutableCopy] ;
    int num = 0;

    for (int j = 0; j < subString.length; j ++) {
    NSString *word = [subString substringWithRange:NSMakeRange(j, 1)];

    if (node[word] == nil) {
    break;
    }else{
    num ++;
    node = node[word];
    }

    //敏感词匹配成功
    if ([node[EXIST]integerValue] == 1) {

    NSMutableString *symbolStr = [NSMutableString string];
    for (int k = 0; k < num; k ++) {
    [symbolStr appendString:@"*"];
    }

    [result replaceCharactersInRange:NSMakeRange(i, num) withString:symbolStr];

    i += j;
    break;
    }
    }
    }

    return result;
    }

    - (void)freeFilter{
    self.root = nil;
    }

    - (void)stopFilter:(BOOL)b{
    self.isFilterClose = b;
    }

    参考链接:

    https://www.cnblogs.com/myvic/p/8671991.html

    https://blog.csdn.net/Jali_li/article/details/52843576(代码主要是这个亲的,赞一个)

  • 相关阅读:
    响应式布局
    C# 基础复习 二 面向对象
    C# 基础复习 一 数据类型
    .net 面试题
    Unity5.X 创建基本的3D游戏场景
    Unity5.X 编辑器介绍
    Unity5.X 开发资源介绍
    SignalR
    vue-cli
    Vue.js
  • 原文地址:https://www.cnblogs.com/isItOk/p/4986246.html
Copyright © 2011-2022 走看看