58同城,春招笔试题:求n个相同字串(O(n))

package com.tangbaobao.baidu;

import org.junit.Test;

/**
 * 58笔试题
 *
 * @author tangyaya8
 * @create 2018/04/02
 **/

public class FiveEight {
    @Test
    public void fun1() {
        String string = "aaaajjddddinfdfyyyy2222";
        int n = 4;
        this.isExitString(string, n);
    }

    /**
     * 是否有存在n个连续的字符串
     * 编程题1:输入一个字符串,输入整数n,找出长度为n的相同字符构成的子串。
     * @param string
     * @param n
     */
    public void isExitString(String string, int n) {
        //定义两个指针
        int start = 0;
        int end = 1;
        //记录字符串
        StringBuffer temp = new StringBuffer();

        char[] chars = string.toCharArray();
            temp.append(chars[start]);
        while (start < chars.length && end < chars.length) {
            if (chars[start] == chars[end]) {
                end++;
                temp.append(chars[start]);
                //处理最后的情况
                if(end == chars.length && temp.length() == n){
                    System.out.println("(" + start + "," + (end-1) + "," + temp + ")");
                }
            } else {
                if (temp.length() == n) {
                    System.out.println("(" + start + "," + (end-1) + "," + temp + ")");
                }
                start = end - 1;
                start++;
                end++;
                temp = new StringBuffer();
                temp.append(chars[start]);
            }
        }
    }
}

写的有点累赘,😂

#春招#
全部评论
就是leetcode上面一道叫count and say的题
点赞 回复 分享
发布于 2018-04-04 15:14
题目都不说清楚就上代码
点赞 回复 分享
发布于 2018-04-04 15:11

相关推荐

ResourceUt...:楼主有自己的垃圾箱,公司也有自己的人才库
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务