输出该数字以及重复序列的单个字符

时间:2015-05-18 04:11:58

标签: java

人们!我一直在Java上练习不同的任务,这个已经花了我一段时间才弄明白。用户只需输入String个字母,例如,如果用户输入的内容为wwwzddfffff,则输出应为3w1z2d5f或另一个示例kklllk和输出应该是3k3l。方法runLength()接受每个重复字符的出现,并输出该数字以及重复序列的单个字符 我得到的是:

Enter any String: 
wwwwzzzz
7z




    import java.util.Scanner;

public class RunLength {

    public static void main(String[] args)
    {
        Scanner kbd = new Scanner(System.in);
        System.out.println("Enter any String: ");
        String word = kbd.nextLine();
        String result = runLength(word);
        System.out.println(result);
    }

    public static String runLength(String word)
    {
        char[] chars = word.toCharArray();
        char firstChar = chars[0];
        char temp = 0;
        int count = 0;
        String result = "";

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

            if(firstChar == chars[i])
            {
                temp = firstChar;
                count++;
                result = count+""+temp;
            }

            else if(firstChar != chars[i])
            {
                temp = chars[i];
                count++;
                result = count+""+temp;
            }
        }

        return result;
    }

}

3 个答案:

答案 0 :(得分:1)

NSString *data = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"quakes" ofType:@"csv"] encoding:NSASCIIStringEncoding error:nil];
NSArray *lines = [data componentsSeparatedByString:@"\n"];

    NSInteger count = lines.count - 1;

    TBQuadTreeNodeData *dataArray = malloc(sizeof(TBQuadTreeNodeData) * count);
    for (NSInteger i = 0; i < count; i++) {
        dataArray[i] = TBDataFromLine(lines[i]);
    }

    TBBoundingBox world = TBBoundingBoxMake(19, -166, 72, -53);
    _root = TBQuadTreeBuildWithData(dataArray, count, world, 4);

答案 1 :(得分:0)

希望您重写runLength方法。

public static Map runLength(String word) {
        char[] chars = word.toCharArray();
        char firstChar = chars[0];
        Map charMap = new HashMap();

        for(int i = 0; i < chars.length; i++) {
            if(charMap.contains(chars[i])
                charMap.put(chars[i],++charMap.get(chars[i]));
            else
               charMap.put(chars[i],1);
        }
        return charMap;
    }

//在主方法

Map myMap = runLength(word);

for (Entry entry : myMap.entrySet()) {
    System.out.print(myMap.get(entry.getKey())+entry.getKey());
}

答案 2 :(得分:0)

听起来像HashMap会解决您的问题。试试:

 Map<Character, Integer> counter = new HashMap<Character, Integer>();
    char[] chars = word.toCharArray();
    for(char c: chars){
        if(counter.containsKey(c)){
            counter.put(c, c.get(c) ++);
        }
        else{
            counter.put(c, 1);
        }
    }

然后打印:

StringBuilder builder = new StringBuilder();
for (Character c : counter.keySet()) {
        builder.append(c);
        builder.append(counter.get(c));
}

return builder.toString();