(暴力求解)Encoding HDU1020

Encoding 

連接:http://acm.hdu.edu.cn/showproblem.php?pid=1020php

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 55038    Accepted Submission(s): 24576
java

Problem Description
Given a string containing only 'A' - 'Z', we could encode it using the following method:

1. Each sub-string containing k same characters should be encoded to "kX" where "X" is the only character in this sub-string.

2. If the length of the sub-string is 1, '1' should be ignored.
 
Input
The first line contains an integer N (1 <= N <= 100) which indicates the number of test cases. The next N lines contain N strings. Each string consists of only 'A' - 'Z' and the length is less than 10000.
 
Output
For each test case, output the encoded string in a line.
 
Sample Input
2
ABC
ABBCCC
 
Sample Output
ABC
A2B3C
 
Author
ZHANG Zheng

能夠用暴力求解法求解。ios

JAVA代碼以下:less

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner inScanner = new Scanner(System.in);
        int num = inScanner.nextInt();
        inScanner.nextLine();
        while(num-->0) {
            String string = inScanner.nextLine();
            string+="a";//這個要注意,防止接下來的統計時會有溢出的。 int sum = 1;
            for(int i = 0;i < string.length()-1;i++) {
                if(string.charAt(i) == string.charAt(i+1)) {   
sum
++; } else { if(sum==1) { System.out.print(string.charAt(i)); } else { System.out.print(sum + "" + string.charAt(i)); sum = 1; } } } System.out.println();//這個很迷,我以前因爲用了String.out.print("\n");而WA了好幾回。。。。。。
} } }

 

C++代碼:this

#include<iostream>
#include<string>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        string a;
        cin>>a;
        int len=a.length();
        int sum=1;
        for(int i=0;i<len;i++)
        {
            if(a[i]==a[i+1])
            {
                sum++;
            }
            else
            {
                if(sum==1)
                {
                    cout<<a[i];
                    sum=1;
                 }
                else
                {
                    cout<<sum<<a[i];
                    sum=1;
                }
            }
        }
        cout<<endl;
    }
    return 0;
}
相關文章
相關標籤/搜索