我陷入了Java中与问题相关的字符串之一。我的逻辑在某些测试用例中效果很好,但在所有测试用例中却并非如此。请向我建议以下问题的实际逻辑:

我得到了一个n字符的字符串s,仅包括A和B。我可以选择任何索引i并将s(i)更改为A或B。找到最小值。必须对字符串S进行的更改,以使结果字符串的格式为:AAAAA ..... BBBBB。换句话说,我的任务是确定最小编号。的变化,以使字符串s具有x no。开头是A,然后是其余(n-x)号。的。

样本输入如下
4
3
AAB
5
阿巴
1个

4
巴巴

第一行:一个整数,表示测试用例的数量
对于每个测试用例:
第一行包含一个整数,表示字符串的大小
第二行包含字符串

我的代码如下

import java.util.*;
class TestClass {
    public static void main(String args[] ) throws Exception {
        Scanner s = new Scanner(System.in);
        TestClass t = new TestClass();
        int test_case = s.nextInt();
        for(int i = 0; i < test_case; i++){
            int len = s.nextInt();
            String none = s.nextLine();
            String str = s.nextLine();
            int cnta = t.count_ab(str,'A');
            int cntb = t.count_ab(str,'B');
            char c1 = '1';
            if(cnta > cntb){
                c1 = 'A';
            }
            else{
                c1 = 'B';
            }
            int count = 0;
            int c1_count = 0;
            int c2_count = 0;
            if(str.length() > 1){
                String rev = "";
                c1_count = t.cnt_init_a(str, 'A');
                StringBuilder sb = new StringBuilder(str);
                rev = sb.reverse().toString();
                c2_count = t.cnt_init_a(rev, 'B');
                int rem_len = str.length() - c2_count;
                for(int h = c1_count; h < rem_len; h++){
                    if(Character.compare(str.charAt(h), c1) != 0){
                        count = count + 1;
                    }
                }

            }
            System.out.println(count);
        }
    }

    public int cnt_init_a(String str, char c){
        int cnt = 0;
        for(int l = 0; l < str.length(); l++){
            if(Character.compare(str.charAt(l), c) == 0){
                cnt = cnt + 1;
            }
            else{
                break;
            }
        }
        return cnt;
    }

    public int count_ab(String str, char c){
        int cnt = 0;
        for(int g = 0; g < str.length(); g++){
            if(Character.compare(str.charAt(g), c) == 0){
                cnt = cnt + 1;
            }
        }
        return cnt;
    }

最佳答案

您的逻辑失败,例如"BAAAAAAAAAABBBBBBBBBB""AAAAAAAAAABBBBBBBBBBA"

您应该首先忽略所有前导A和所有尾随B,因为它们永远都不应更改。

"BAAAAAAAAAABBBBBBBBBB"-> "BAAAAAAAAAA"(删除了结尾的B)
"AAAAAAAAAABBBBBBBBBBA"-> "BBBBBBBBBBA"(已删除前导A)

然后将前导B更改为A,或将尾随A更改为B,以较短者为准。

然后重复该过程。

09-11 18:31
查看更多