【发布时间】:2016-01-27 21:52:34
【问题描述】:
我在完成这项任务时遇到了问题:
给定一个字符串,将第一次出现的“a”替换为“x”,第二次出现的“a”替换为“xx”,第三次出现的“a”替换为“xxx”。第三次出现后,以“x”、“xx”、“xxx”……等重新开始替换模式;但是,如果一个 'a' 后面连续有 2 个以上的其他 'a' 字符,则不要替换该 'a' 之后的任何更多 'a' 字符。
不允许使用替换方法。
aTo123X("ababba") → "xbxxbbxxx"
aTo123X("anaceeacdabnanbag") → "xnxxceexxxcdxbnxxnbxxxg"
aTo123X("aabaaaavfaajaaj") → "xxxbxxxaaavfaajaaj"
aTo123X("pakaaajaaaamnbaa") → "pxkxxxxxxjxxaaamnbaa"
aTo123X("aaaak") → "xaaak"
我的代码输出包含 a,添加了 x,但 x 的数量不正确。
public String aTo123X(String str) {
/*
Strategy:
get string length of the code, and create a for loop in order to find each individual part of the String chars.check for a values in string and take in pos of the a.
if one of the characters is a
replace with 1 x, however, there aren't more than 2 a's immediately following first a and as it keeps searching through the index, add more x's to the original string, but set x value back to 1 when x reaches 3.
if one of characters isn't a,
leave as is and continue string.
*/
String xVal = "";
String x = "x";
String output = "";
for (int i = 0; i < str.length(); i++){
if( str.charAt(i) == 'a'){
output += x;
str.substring(i+1, str.length());
}
output += str.charAt(i);
}
return output;
}
【问题讨论】:
-
有什么问题?
-
@MarounMaroun 当我返回它时,它不会删除 a,而只是添加 x,而且太多了
-
@Shivam 这里,'a' 之后不需要发生任何变化是 'aaa' 第一次出现的第一个 'a'。只需再仔细阅读您的评论一次,您就会明白。