gpt4 book ai didi

java - 两个字符的构造模式(例如 : "aabba" ,"aba")

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:43:45 24 4
gpt4 key购买 nike

在给定两个字符的出现频率(例如:x = 5)的情况下,建议一种使用两个字符(例如:“aabba”、“aba”)的模式构造 String 的有效方法, y = 4).问题是任何字符都不应重复超过两次。

示例测试用例:

|  X  |  Y  | Output     |
| --- | --- | ---------- |
| 3 | 2 | aabab |
| 2 | 1 | aab |
| 4 | 6 | bbabbababa |
| 4 | 4 | abababab |

我写了一个贪心的方法如下,

public static String getPatternStr(int x, int y){
String result = "";
List<String> list = new ArrayList<>();
int secondIterationIndex = 0;

int moreCharCount = (x > y)? x : y;
int lessCharCount = (x < y)? x : y;


String moreChar = (x > y)?"a":"b";
String lessChar = (x < y)?"a":"b";

if(x == y){
moreCharCount = lessCharCount = x;
moreChar = "a";
lessChar = "b";
}

for(int i = 1; i <= (x+y); i++){
if(lessCharCount > 0){
if(i%2 == 1){
list.add(moreChar);
moreCharCount--;
}
else{
list.add(lessChar);
lessCharCount--;
}
}else{
list.add(secondIterationIndex,moreChar);
secondIterationIndex += 3;
if(secondIterationIndex > list.size()){
secondIterationIndex = list.size()-1;
}
}
//System.out.println(list);
}
for(String e: list){
result += e;
}
return result;
}

这种方法看起来很繁琐,也不优雅。请问有什么更好更有效的方法吗?

编辑:我坚信有一种使用这些(x 和 y)数字的方法,我们甚至可以在循环开始之前计算双 a、双 b、单 a 和单 b 的数量。只有部分工作逻辑。

public static String patternStr(int x, int y){
String result = "";

int large = (x > y)? x : y;
int small = (x < y)? x : y;


int pairsOfLarge = large/2;
int largeParts = pairsOfLarge + large%2;

int minSmallParts = (largeParts>1)? (largeParts-1):1;
int pairsOfSmall = small - minSmallParts;
int smallParts = pairsOfSmall + (small - (pairsOfSmall*2));
// System.out.println("minSmallParts="+minSmallParts+" pairsOfSmall="+pairsOfSmall+" smallParts="+smallParts);

String odd = (large == x)?"a":"b";
String even = (small == x)?"a":"b";

int i = 1;
while((largeParts + smallParts) > 0){
if(i%2 > 0){
if(pairsOfLarge > 0){
result += odd + odd;
pairsOfLarge--;
}else{
result += odd;
}
largeParts--;
}else{
if(pairsOfSmall > 0){
result += even + even;
pairsOfSmall--;
}else{
result += even;
}
smallParts--;
}
i++;
}
return result;
}

最佳答案

这对我来说更优雅(算法的工作是相似的):

static String getPatternStr(int x, int y){
int lessCharCount = Math.min(x,y);
int moreCharCount = Math.max(x,y);
String moreChar = "a";
String lessChar = "b";
if(lessCharCount < (moreCharCount + 1) / 2 - 1)
return "";
if(lessCharCount == 1 && moreCharCount == 1)
return moreChar + lessChar;
LinkedList<String> result = new LinkedList<>(Arrays.asList(moreChar.repeat(moreCharCount).split("")));
for(int i = 2; lessCharCount > 0; i = (i + 3) % (++moreCharCount)){
result.add(i,lessChar);
lessCharCount--;
}
return result.stream().collect(Collectors.joining(""));
}

没有太大的效率提升,只是使用了LinkedList而不是ArraysList,前者更适合插入操作。

关于java - 两个字符的构造模式(例如 : "aabba" ,"aba"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57424992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com