count-the-repetitions

本文探讨了LeetCode上一道关于字符串重复计数的问题,并提供了几种不同的解决方案。其中包括一种使用额外数组进行优化的方法,以及一个更为简洁的遍历比较方法。尽管进行了优化,但在某些情况下仍会出现超时问题。

https://leetcode.com/problems/count-the-repetitions/

下面是我的方法,结果对的,超时了。。。

package com.company;


class Solution {
    public int getMaxRepetitions(String s1, int n1, String s2, int n2) {
        int len1 = s1.length();
        int[][]stores = new int[26][len1];
        int[] pos = new int[26];
        int[] cur = new int[26];
        int index;

        for (int i=0; i<len1; i++) {
            index = s1.charAt(i)-'a';
            stores[index][pos[index]] = i;
            pos[index] = pos[index] + 1;
        }

        int curPos = 0;
        int ret = 0;
        int len2 = s2.length();
        while (true) {

            for (int i=0; i<n2; i++) {
                for (int j=0; j<len2; j++) {
                    index = s2.charAt(j) - 'a';

                    if (cur[index] >= pos[index] * n1) {

                        return ret;
                    }

                    int newPos = 0;
                    do {
                        newPos = cur[index] / pos[index] * len1 + stores[index][cur[index] % pos[index]];
                        cur[index] = cur[index] + 1;
                    } while (newPos < curPos && cur[index] < pos[index] * n1);

                    if (newPos < curPos) {
                        return ret;
                    }
                    curPos = newPos + 1;


                }
            }
            ret++;

        }

    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        String s1 = "niconiconi";
        int n1 = 99981;
        String s2 = "nico";
        int n2 = 81;

        Solution solution = new Solution();
        int ret  = solution.getMaxRepetitions(s1, n1, s2, n2);

        // Your Codec object will be instantiated and called as such:
        System.out.printf("ret:%d\n", ret);

        System.out.println();

    }

}

 

优化之后的结果,还是超时:

加了string到array的优化,另外每次循环之后坐个判断剪枝。

 

package com.company;


class Solution {
    public int getMaxRepetitions(String s1, int n1, String s2, int n2) {
        int len1 = s1.length();
        int[][]stores = new int[26][len1];
        int[] pos = new int[26];
        int[] cur = new int[26];
        int index;

        for (int i=0; i<len1; i++) {
            index = s1.charAt(i)-'a';
            stores[index][pos[index]] = i;
            pos[index] = pos[index] + 1;
        }

        int curPos = 0;
        int ret = 0;
        int len2 = s2.length();
        char[] array2 = s2.toCharArray();
        while (true) {

            for (int i=0; i<n2; i++) {
                for (int j=0; j<len2; j++) {
                    index = array2[j] - 'a';

                    int newPos = 0;
                    while (cur[index] < pos[index] * n1) {
                        newPos = cur[index] / pos[index] * len1 + stores[index][cur[index] % pos[index]];
                        cur[index] = cur[index] + 1;
                        if (newPos >= curPos) {
                            break;
                        }
                    }

                    if (newPos < curPos) {
                        /*System.out.printf("index %d cur[index] %d pos[index] %d cur/-pos %d, store %d\n",
                                index, cur[index], pos[index], cur[index] % pos[index], stores[index][cur[index] % pos[index]]);

                        System.out.printf("newPos %d curPos %d\n",
                                newPos, curPos);
                                */
                        return ret;
                    }
                    curPos = newPos + 1;


                }
            }
            ret++;
            for (int i=0; i<26; i++) {
                if (pos[i] > 0 && cur[i] >= pos[i] * n1) {
                    return ret;
                }
            }

        }

    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        String s1 = "acb";
        int n1 = 4;
        String s2 = "ab";
        int n2 = 2;

        Solution solution = new Solution();
        int ret  = solution.getMaxRepetitions(s1, n1, s2, n2);

        // Your Codec object will be instantiated and called as such:
        System.out.printf("ret:%d\n", ret);

        System.out.println();

    }

}

 

用了这种Brute Force的方法,居然比我的快。。。。。。

public class Solution {
    public int getMaxRepetitions(String s1, int n1, String s2, int n2) {
        char[] array1 = s1.toCharArray(), array2 = s2.toCharArray();
        int count1 = 0, count2 = 0, i = 0, j = 0;
        
        while (count1 < n1) {
            if (array1[i] == array2[j]) {
                j++;
                if (j == array2.length) {
                    j = 0;
                    count2++;
                }
            }
            i++;
            if (i == array1.length) {
                i = 0;
                count1++;
            }
        }
        
        return count2 / n2;
    }
}

 

(完)

 

int SNMP_Process_Next_PDU(SNMP_PKT_T *pktp) { VB_T *vbp, *newvbp, *oldvbp; INT_32_T maxreps = 1, *err_stat; int nonreps = 0, count, indx; /* We will be looking at the error status a lot so we get a local pointer to it to make things easier */ err_stat = &(pktp->pdu.std_pdu.error_status); /* get some initial information */ oldvbp = pktp->pdu.std_pdu.std_vbl.vblist; count = pktp->pdu.std_pdu.std_vbl.vbl_count; #if ENVOY_USE_V2_PROTOS DYNCFG_IFCFGVBL_BEGIN(envoy_use_v2_protos) if (pktp->pdu_type == GET_BULK_REQUEST_PDU) { ALENGTH_T need; /* Test the packet and see if even an empty var bind list will casue a too big, if so we drop the packet. We've already saved the vblist and count so we 0 those fields and do a bufsize check, then restore the fields. */ pktp->pdu.std_pdu.std_vbl.vblist = 0; pktp->pdu.std_pdu.std_vbl.vbl_count = 0; need = SNMP_Bufsize_For_Packet(pktp); pktp->pdu.std_pdu.std_vbl.vblist = oldvbp; pktp->pdu.std_pdu.std_vbl.vbl_count = count; if (pktp->maxpkt < need) { SGRPv2_INC_COUNTER(snmp_stats.snmpSilentDrops); /* sar may need to add a different return here */ pktp->error_complete(&pktp->pkt_src, &pktp->pkt_dst, 1, pktp->async_cookie,pktp->vrfID); return(1); } /* Pull the maxreps and nonreps information from the packet and rationalize it. */ maxreps = pktp->pdu.std_pdu.error_index; if (*err_stat < 0) nonreps = 0; else if (*err_stat >= count) { nonreps = count; maxreps = 1; } else nonreps = (int)(*err_stat & 0xFFFF); if (maxreps < 1) { maxreps = 1; /* This is kinda wierd, the manager sent a bulk packet but doesn't want any of the repeaters, adjust the counters */ if (nonreps == 0) { Clean_vb_list(&pktp->pdu.std_pdu.std_vbl); pktp->pdu.std_pdu.std_vbl.vblist = 0; pktp->pdu.std_pdu.std_vbl.vbl_count = 0; } count = nonreps; } } DYNCFG_IFCFGVBL_END(envoy_use_v2_protos) #endif /* #if ENVOY_USE_V2_PROTOS */ /* assume the packet will work */ *err_stat = NO_ERROR; pktp->pdu.std_pdu.error_index = 0; /* Check to see if the user actually wants anything, if not we are done and we bail out, note that this test must happen after we set the err status & index fields to 0 */ if ((oldvbp == 0) || (count == 0)) return(0); /* Fill in the max_reps and non_reps fields. If this is a bulk packet we pulled the information from the error fields. If it isn't a bulk packet we are using default values */ pktp->pdu.std_pdu.max_reps = maxreps; pktp->pdu.std_pdu.non_reps = nonreps; /* Some errors may require us to use the original list so we save the original and allocate space for a new one. The objid for the new vbs will be filled in by the find_next_object routine, but we will need to clone the object id if find_next_object tells us their aren't any more objects. */ if ((newvbp = VarBindList_Allocate(count)) == 0) { ENVOY_Send_SNMP_Error_Packet(pktp, GEN_ERR, 0); return(1); } pktp->pdu.std_pdu.saved_vbl.vbl_count = pktp->pdu.std_pdu.std_vbl.vbl_count; pktp->pdu.std_pdu.saved_vbl.vblist = oldvbp; pktp->pdu.std_pdu.std_vbl.vbl_count = count; pktp->pdu.std_pdu.std_vbl.vblist = newvbp; /* Try to get the infrastructure lock, we release it using the ENVOY_AX_MA_RELEASE_WRITE_LOCK macro */ #if (INSTALL_ENVOY_AGENTX_MASTER && INSTALL_ENVOY_SNMP_LOCK) DYNCFG_IFCFGVBL_BEGIN(agentx_master_component) if (ENVOY_SNMP_GET_WRITE_LOCK(SNMP_infrastructure_lock)) { BUG(BUG_ENVOY_LOCKING, BUG_CONTINUABLE, 0, (BUG_OUT, "SNMP_Process_Next_PDU: infrastructure lock broken", 0)); ENVOY_Send_SNMP_Error_Packet(pktp, GEN_ERR, 0); return(1); } DYNCFG_IFCFGVBL_END(agentx_master_component) #endif /* If necessary try to find the view index structure, if we want to do rfc1445 view checking find_object_node will expect this routine to have been run and to have inserted a pointer into pktp */ #if (INSTALL_ENVOY_SNMP_DYNAMIC_VIEWS) if (SNMP_View_Find_Family(pktp) && (pktp->snmp_version == SNMP_VERSION_3)) { ENVOY_AX_MA_RELEASE_WRITE_LOCK(SNMP_infrastructure_lock); ENVOY_Send_SNMP_Error_Packet(pktp, AUTHORIZATION_ERROR, 0); return(1); } #endif /* Attempt to find all the requested objects Note: if we find an error we set indx = count to break the loop */ for(indx = 0, vbp = newvbp; indx < count; indx++, vbp++, oldvbp++) { if(NULL == vbp || NULL == oldvbp || NULL == pktp) break; switch(find_next_object(vbp, &(oldvbp->vb_obj_id), pktp, 1)) { case 0: /* Nothing was found, generate an error for v1 or an exception for v2 */ switch(pktp->snmp_version) { #if INSTALL_ENVOY_SNMP_VERSION_1 case SNMP_VERSION_1: /* If version 1 we send a NO_SUCH_NAME error back. We set up the packet for a nosuch name error. */ *err_stat = NO_SUCH_NAME; pktp->pdu.std_pdu.error_index = SNMP_ERROR_INDEX(indx); indx = count; break; #endif #if ENVOY_USE_V2_PROTOS case SNMP_VERSION_2: case SNMP_VERSION_3: default: DYNCFG_IFCFGVBL_BEGIN(envoy_use_v2_protos) /* If not version 1 we send a END_OF_MIB exception back. We set the data_flags_n_type of the current vbp to END_OF_MIB, clone the object id and tag the vbp as having been done and continue with the rest */ vbp->vb_data_flags_n_type = VT_ENDOFMIB; vbp->vb_flags |= VFLAG_NEXT_STARTED | VFLAG_NEXT_DONE; if (clone_object_id(&oldvbp->vb_obj_id, &vbp->vb_obj_id)) { /* We were unable to clone an object so we return a gen err */ *err_stat = GEN_ERR; indx = count; } DYNCFG_IFCFGVBL_END(envoy_use_v2_protos) break; #endif /* #if ENVOY_USE_V2_PROTOS */ } break; case -1: /* An internal error occurred send back a generr */ *err_stat = GEN_ERR; indx = count; break; } /* switch(find_next_object...) */ } /* for(indx = 0...) */ ENVOY_AX_MA_RELEASE_WRITE_LOCK(SNMP_infrastructure_lock); if (*err_stat) { ENVOY_Send_SNMP_Error_Packet(pktp, *err_stat, pktp->pdu.std_pdu.error_index); return(1); } /* Now we loop through the vblist again and start all the nexts */ for(vbp = newvbp; count; count--, vbp++) { /* If the next started flag is set then either we set it above or the nextproc of some other var bind has claimed responsibility for this var bind. In either case we skip this var bind and continue */ if (vbp->vb_flags & (VFLAG_NEXT_STARTED | VFLAG_NEXT_DONE)) continue; ((vbp->vb_ml.ml_leaf)->nextproc) (vbp->vb_ml.ml_last_match, vbp->vb_ml.ml_remaining_objid.num_components, vbp->vb_ml.ml_remaining_objid.component_list, pktp, vbp); vbp->vb_flags |= VFLAG_NEXT_STARTED; /* test the error code, if we had an error then mark any remaining vbs as having been gotten (so we won't trip over them later). We need to skip the first vb as that is the one that caused the failure. Then break because we are done */ if (*err_stat) { for (vbp++, count--; count; count--, vbp++) if (!(vbp->vb_flags & VFLAG_NEXT_STARTED)) vbp->vb_flags |= VFLAG_NEXT_STARTED | VFLAG_NEXT_DONE; break; } } return(0); } 详细解析这个函数
最新发布
11-25
SNMPv2 defines the get-bulk operation, which allows a management application to retrieve a large section of a table at once. The standard get operation can attempt to retrieve more than one MIB object at once, but message sizes are limited by the agent's capabilities. If the agent can't return all the requested responses, it returns an error message with no data. The get-bulk operation, on the other hand, tells the agent to send as much of the response back as it can. This means that incomplete responses are possible. Two fields must be set when issuing a get-bulk command: nonrepeaters and max-repetitions. Nonrepeaters tells the get-bulk command that the first N objects can be retrieved with a simple get-next operation. Max-repetitions tells the get-bulk command to attempt up to Mget-next operations to retrieve the remaining objects.   Assume we're requesting three bindings: sysDescr, ifInOctets, and ifOutOctets. The total number of variable bindings that we've requested is given by the formula N + (M * R), where N is the number of nonrepeaters (i.e., scalar objects in the request -- in this case 1, because sysDescr is the only scalar object), M is max-repetitions (in this case, we've set it arbitrarily to 3), and R is the number of nonscalar objects in the request (in this case 2, because ifInOctets and ifOutOctets are both nonscalar). Plugging in the numbers from this example, we get 1 + (3 * 2) = 7, which is the total number of variable bindings that can be returned by this get-bulk request.   The Net-SNMP package comes with a command for issuing get-bulk queries. If we execute this command using all the parameters previously discussed, it will look like the following:   $ snmpbulkget -v2c -B 1 3 linux.ora.com public sysDescr ifInOctets ifOutOctets   system.sysDescr.0 = "Linux linux 2.2.5-15 #3 Thu May 27 19:33:18 EDT 1999 i686"   interfaces.ifTable.ifEntry.ifInOctets.1 = 70840   interfaces.ifTable.ifEntry.ifOutOctets.1 = 70840   interfaces.ifTable.ifEntry.ifInOctets.2 = 143548020   interfaces.ifTable.ifEntry.ifOutOctets.2 = 111725152   interfaces.ifTable.ifEntry.ifInOctets.3 = 0   interfaces.ifTable.ifEntry.ifOutOctets.3 = 0   Since get-bulk is an SNMPv2 command, you have to tell snmpgetbulk to use an SNMPv2 PDU with the -v2c option. The nonrepeaters and max-repetitions are set with the -B 1 3 option. This sets nonrepeaters to 1 and max-repetitions to 3. Notice that the command returned seven variable bindings: one for sysDescr and three each for ifInOctets and ifOutOctets.            Non-repeaters and maxRepetitions   They are used in getBulk.   Definition of Non-repeaters:- The Non-repeater specifies the number of variables in the variable-bindings list for which a single OID (lexicographic successor) is to be returned.      Definition of maxRepetitions :- The max-repetitions specifies the number of OIDs (lexicographic successor)to be returned for the remaining variables (total variables - nonrepeaters)in the variable bindings list.      For clearer understanding, Let us assume Nonrepeater=4, and Max-Repetitions=3;      If get values with OID lists which are .1.3.6.1.2.1.11.1.0, .1.3.6.1.2.1.11.2.0 , .1.3.6.1.2.1.11.3.0, .1.3.6.1.2.1.11.4.0, .1.3.6.1.2.1.11.5.0, .1.3.6.1.2.1.11.6.0 , and the method is getNext.      NonRepeater value is 4. So the first four variable returns a single lexicographic successor.   Request OIDs ----> Response   .1.3.6.1.2.1.11.1.0 ---> .1.3.6.1.2.1.11.2.0 and its value   .1.3.6.1.2.1.11.2.0 ---> .1.3.6.1.2.1.11.3.0 and its value   1.3.6.1.2.1.11.3.0 ---> .1.3.6.1.2.1.11.4.0 and its value   .1.3.6.1.2.1.11.4.0 ---> .1.3.6.1.2.1.11.5.0 and its value      The subsequent OIDs in the OIDs list to be returned the number of max-repetitions lexicographic successor.   Request ---> Response   .1.3.6.1.2.1.11.5.0 --> .1.3.6.1.2.1.11.6.0, .1.3.6.1.2.1.11.7.0, .1.3.6.1.2.1.11.8.0 and its value.      Request ---> Response   .1.3.6.1.2.1.11.6.0 --> .1.3.6.1.2.1.11.7.0, .1.3.6.1.2.1.11.8.0 , .1.3.6.1.2.1.11.9.0 and its value.      So the response will be,      .1.3.6.1.2.1.11.2.0 and its value   .1.3.6.1.2.1.11.3.0 and its value   .1.3.6.1.2.1.11.4.0 and its value   .1.3.6.1.2.1.11.5.0 and its value   .1.3.6.1.2.1.11.6.0 and its value   .1.3.6.1.2.1.11.7.0 and its value   .1.3.6.1.2.1.11.7.0 and its value   .1.3.6.1.2.1.11.8.0 and its value   .1.3.6.1.2.1.11.8.0 and its value   .1.3.6.1.2.1.11.9.0 and its value
11-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值