美文网首页
java字符串面试题,从一个字符串中查找子串

java字符串面试题,从一个字符串中查找子串

作者: 提米锅锅 | 来源:发表于2019-09-29 22:52 被阅读0次

    一个常规的字符串查找算法,两层循环,每次会记录之前匹配到的字串,完整匹配后程序会退出,如果要优化的话,需要使用KMP算法,大家可以百度,比较复杂。

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @Slf4j
    public class findSubStringNormalTest {
        @Test
        public void run() {
            String text = "xxb abbbb ccc add adddxdd";
            String pat = "addd";
            int matchlen = 0;
            for (int i = 0; i < text.length(); i++) {
                //外层循环控制目标文本偏移量
                for (int j = 0; j < pat.length(); j++) {
                    //开始匹配
                    if (pat.charAt(j) == text.charAt(i + j)) {
                        matchlen++;
                        if (matchlen == pat.length()) {
                            log.info("final match :" + text.substring(i, i + j + 1));
                            break;
                        }
                    } else {
                        //记录每次匹配到的子串
                        if (matchlen > 0) {
                            log.info("match:" + text.substring(i, i + j + 1));
                        }
                        matchlen = 0;
                        break;
                    }
    
                }
            }
        }
    }
    
    

    程序输出

    com.example.findSubStringNormalTest       : match:ab
    com.example.findSubStringNormalTest       : match:add 
    com.example.findSubStringNormalTest       : final match :addd
    

    相关文章

      网友评论

          本文标题:java字符串面试题,从一个字符串中查找子串

          本文链接:https://www.haomeiwen.com/subject/zsgqpctx.html