第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算從旋轉字符串中找到原始字符串所需的旋轉次數的替代方法

計算從旋轉字符串中找到原始字符串所需的旋轉次數的替代方法

慕田峪4524236 2022-11-02 10:35:26
我們得到了 2 根弦,一根是正確的,一根是旋轉的?我們必須告訴我們,在第二根弦旋轉多少步后,我們得到原始(第一)弦(假設只允許一側旋轉)但這里的問題是一次旋轉一個字符的字符串然后將旋轉的字符串與原始字符串進行比較的傳統(tǒng)方法花費的時間比允許的要多,可以使用哪種替代方法?字符串 1:字符串david 2:vidda(首先處理部分旋轉:avidd,第二個:david,所以答案是 2)輸出:2
查看完整描述

2 回答

?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

String one = "david"; 

String two = "vidda";


one.concat(one).indexOf(two) 

會工作,不是嗎?


查看完整回答
反對 回復 2022-11-02
?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

我不知道我的方法是否足夠快......但它的運行時間是字符串的長度在O(n)哪里。n


這種方法只有在它是可解的并且兩個字符串具有相同長度的情況下才有效:


public static void main(String[] args) {

    String string1 = "david";

    String string2 = "avidd";

    char[] a = string1.toCharArray();

    char[] b = string2.toCharArray();

    int pointer = a.length-1;

    int off = 0;

    int current = 0;

    for (int i = b.length-1; i >= 0; i--) {

        if (b[i] == a[pointer]) {   //found a match

            current++;              //our current match is one higher

            pointer--;              //pointer of string1 goes one back

        } else if (current != 0) {  //no match anymore and we have had a match

            i ++;                   //we have to recalculate the actual position in the next step of the loop

            off += current;         //we have to rotate `current` times more

            current = 0;            //reset current match

            pointer = a.length-1;   //reset pointer

        } else {                    //no match and we didn't have had a match the last time

            off ++;                 //we have to rotate one more time

        }

    }

    System.out.println("Rotate: " + off);

}

基本上它從兩個字符串的末尾開始并回到開頭,直到它不再有任何差異。如果它在任何時候確實有差異,它會將當前計數器添加off到string1.


我的算法在完成旋轉后不檢查字符串是否相同。off


查看完整回答
反對 回復 2022-11-02
  • 2 回答
  • 0 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號