我是java编程的新手,我的要求是
INPUT:" aaabaccuuuou" 输出:" aaaccuuu"
仅返回重复字符,并避免该字符与前一个字符不相邻。
我试过以下代码。但它正在输出" aaaabccuuuuo"
不考虑相邻的角色。请帮助我。
import java.util.LinkedHashSet;
import java.util.Set;
public class Sort {
public static void main(String[] args) {
String str = "aaavvvtccatz";
int i =0;
String o = "";
String lo = "";
int count = 0 ;
char[] chars = str.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
sb.append(character);
}
/*System.out.println(sb.toString());*/
for(int j =0;j<sb.length();j++)
{
String a = sb.substring(j,j+1);
for(i=0;i<str.length();i++)
{
String b = str.substring(i, i+1);
if(b.equals(a) )
{
count = count +1;
lo = lo + a;
}
else
{
count = count;
}
}
/*System.out.println(a);*/
/*System.out.println(count);*/
if(count > 1 )
{
for(int h =0; h <count ;h++)
{
o = o + a ;
}
}
count = 0;
}
System.out.println(o);
}
}
注意:代码质量和标准可能不符合专业水平。因为我正在学习基础知识并且超越我的极限。 请不要通过提供代码来帮助我,通过提供找到输出的逻辑帮助我。谢谢。
答案 0 :(得分:1)
以下代码背后的一般理念是:
index = 0
是不相关的,因为它不符合用例的标准。StringBuilder
以便我们可以改善字符串连接。chars[x - 1]
和当前字符== chars[x]
。你可以试试这个
public static void main(String[] args) {
String str = "aaabaccuuuouu";
StringBuilder builder = new StringBuilder();
char[] chars = str.toCharArray();
boolean unreset = true;
for (int x = 1; x < chars.length; x++) {
if (chars[x - 1] == chars[x]) {
if (unreset) {
builder.append(chars[x - 1]);
unreset = false;
}
builder.append(chars[x]);
} else {
unreset = true;
}
}
System.out.println(builder.toString());
}
示例测试用例:输入:aaabaccuuuouu输出:aaaccuuuuu
答案 1 :(得分:0)
编写以下代码时我遵循的逻辑可以这样概括:
代码:
public static void main(String[ ] args) {
System.out.println(getRepeatingChars("aaabaccuuuou"));
}
public static String getRepeatingChars(String testString){
if(testString == null || testString.equals("") || testString.length() == 1){
return "";
}
String resultString = new String();
char[] charArray = testString.toCharArray();
boolean isInSequance = false;
for(int i = 1; i < charArray.length; i++){
if(charArray[i] == charArray[i-1]){
// current character is same as previous
resultString += charArray[i];
// raise flag that we have found a repeating sequence
isInSequance = true;
}else if(isInSequance){
// the current char is not same es previous but we have just left a sequence so add one more char to result string - the last char from last sequence
resultString += charArray[i-1];
isInSequance = false;
}else if(isInSequance && i == charArray.length - 1){
// add last char in string if it is part of a sequence
resultString += charArray[i];
}
}
return resultString;
}