亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

用不允許出現的次數替換字符串中的所有連續重復項

用不允許出現的次數替換字符串中的所有連續重復項

呼如林 2023-03-31 14:35:31
我需要編寫一個方法,它將一個字符串作為參數并返回一個新字符串,該字符串是通過用'n'該字符串的一個實例替換重復的相鄰字母的每個實例而獲得的。例如,如果"aaabcccd"作為輸入 String 和n =2,它返回"aabccd"。我已經嘗試了以下代碼,但沒有得到預期的輸出String in = "aaadbbb";char[] s = in.toCharArray();int len = s.length;int n = 2;StringBuffer new_s = new StringBuffer("");int count = 1;char prev='\0';for (int i = 0; i < len - 1; i++) {    if (s[i] == s[i + 1]) {       if(count <= n){            new_s.append(s[i]);           count++;        }else{         count=1;       }    } else {        new_s.append(s[i]);    }}   System.out.println(new_s);輸出aaadb -預期-aadbb
查看完整描述

5 回答

?
慕運維8079593

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

可以使用反向引用通過正則表達式魔術來完成。


String in = "aaaaddbbbbc";

int n = 2;

String pattern = String.format("(([a-z])\\2{%d})\\2+", n - 1);

System.out.println(in.replaceAll(pattern, "$1"));

輸出:


ddbbc


解釋:里面的數字{}是n-1。


([a-z])是一個捕獲組,匹配從 a 到 z 的任何單個小寫字母。由于它是表達式中的第二組括號,因此可以引用為2.


(([a-z])\\2{n})意思是“匹配相同字母的 n+1 次重復”。它構成了第一個捕獲組,我們將使用它作為替換


\\2+匹配同一字母的所有額外重復。它們在更換后被丟棄。


查看完整回答
反對 回復 2023-03-31
?
largeQ

TA貢獻2039條經驗 獲得超8個贊

看看這個解決方案。您應該注意輸入字符串中的最后一個字符,因為您只迭代到最后一個字符。


private void replaceConsecutiveDuplicates() {

    String input = "aaadbbb";

    int n = 2;

    StringBuffer sb = new StringBuffer();

    int count = 1;

    char current;


    for( int i = 0; i < input.length(); ++i){

        current = input.charAt(i);

        if (i + 1 < input.length() && current == input.charAt(i + 1)) {

            ++count;

        } else if (count > 1) {

            for(int j = 0; j < n; ++j) {

                sb.append(current);

            }

            count = 1;

        }

        else {

            sb.append(current);

        }

    }

    System.out.println(sb.toString());

}


查看完整回答
反對 回復 2023-03-31
?
www說

TA貢獻1775條經驗 獲得超8個贊

要再添加一個備選方案:


    String in = "aaadbbbjjkllllllopp";

    int n = 2;

    StringBuilder sb = new StringBuilder();

    char temp = in.charAt(0);

    for(int i = 0; i < in.length()-1;){   // note that the incrementation of i is moved to the while loop

        temp = in.charAt(i);            // save current char in temp variable

        int count = 0;

        while (i < in.length() && in.charAt(i) == temp) {   ///iterate as long as you find same chars or hit the end of the string

            i++;

            count++;

        }

        if (count > n){   // if and only if count is greater than max allowed set it to max allowed

            count = n;

        }

        for(int j = 0; j < count; j++){   // append count chars

            sb.append(temp);

        }

    }

    System.out.println(sb.toString());


查看完整回答
反對 回復 2023-03-31
?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

  public static String test(String input, int repetitions) {

    String flag = "";

    String replacement = "";

    String output = input;

    ArrayList<Character> prevLetters = new ArrayList<Character>();


    for(int x = 0; x < input.length(); x++) {

        if(!prevLetters.contains(input.charAt(x))) {

            for(int y = 0; y <= repetitions ; y++) {

                flag += String.valueOf(input.charAt(x));

            }

            if(input.contains(flag)) {

                replacement = flag.substring(0, flag.length()-1);

                while(output.contains(flag)){

                    output = output.replace(flag, replacement);

                }

            }

            flag = "";

            prevLetters.add(input.charAt(x));

        }

    }

    return output;

}

這是我的解決方案,它遵循與您類似的想法。然而,與其比較每個字符值,我認為簡單地檢查規則中的中斷(字符連續出現 n+1 次)并“修復”它會更容易。


如果您有興趣使用您的方法,我注意到的一個潛在問題是您沒有在最后一個 else 中將計數分配給 1。您也沒有機會添加最后一個字符,因為您只在循環持續時間為 len - 1 時在索引“i”處添加字符。


查看完整回答
反對 回復 2023-03-31
?
子衿沉夜

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

我認為你在正確的軌道上。我不確定這是否是一項作業,所以我不想直接給你答案,但這里有一些可能有用的提示:

  1. 您已經在遍歷字符串。這很棒!但是,我認為您想將當前字符與前一個字符進行比較,而不是下一個字符。

  2. 您不需要將輸入轉換為 char 數組來迭代它,只需使用charAt(idx)

  3. 您似乎從不使用 prev,但我認為您在聲明時心中有正確的想法!

  4. 將您的問題分為兩部分:何時更新計數和何時附加字符。您可以在 for 循環中解決這兩個問題,但不要嘗試在同一個 if 語句中同時執行這兩個操作,而是將其分解為多個 if。

要做的三件事是:

  • 更新上一個值

  • 更新計數

  • 更新新字符串

獲得這些的正確順序以及我將留給你的確切實現(再次,因為我不確定這是否是一項任務)

更新:由于其他人發布,這是我的解決方案(使用單個 for 循環):

private String replaceConsecutiveDuplicates(String input, int n) {

    if (input == null || input.length() < n) return input;

    if (n == 0) return "";


    StringBuffer sb = new StringBuffer();


    int count = 1;

    char prev = input.charAt(0);

    sb.append(prev);


    char current;

    for( int i = 1; i < input.length(); i++) {

        current = input.charAt(i);

        if (prev == current) {

            if (++count > n) continue;

        } else {

            count = 1; 

        }

        prev = current;

        sb.append(current);

    }

    return sb.toString();

}


查看完整回答
反對 回復 2023-03-31
  • 5 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

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

公眾號

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