이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

문자열 압축하기

문자열을 입력받아서, 같은 문자가 연속적으로 반복되는 경우에 그 반복 횟수를 표시하여 문자열을 압축하기.

입력 예시: aaabbcccccca

출력 예시: a3b2c6a1

run-length

2014/12/05 22:35

좋은게좋은거

좋은 문제 감사합니다! - 고요정, 2019/01/23 10:48

349개의 풀이가 있습니다.

파이썬 2.7


s = 'aabcccaaaaas'

result = s[0]  # 첫번째 값을 결과에 넣는다
count  = 0   #

for st in s:
    if st == result[-1]:  #
        count += 1
    else:
        result += str(count) + st
        count = 1
result += str(count)

print result


결과:
a2b1c3a5s1

2015/12/29 21:49

hana11

파이썬 3.6

s = "aaaabbbcczzzza"

#초기값을 설정합니다.
result = s[0] #반복문 실행되는 동안 문자열 형태로 반환되는 결과들을 담을 변수
count = 0 #반복되서 나오는 문자 수만큼 카운팅되는 값을 담을 변수

for i in s:
    if i == result[-1]: #result변수 마지막 문자와 비교합니다. else에서 result변수에 값이 추가되기 때문에 마지막 문자[-1]와 비교.
        count += 1
    else:
        result += str(count) + i #마지막 글자와 i가 다를 경우 카운팅된 값을 문자열 형태로 result 변수 마지막에 추가 해주고 i를 마지막 문자로 추가합니다.
        count = 1
result += str(count) #결과들이 담긴 변수에 마지막으로 카운팅된 값을 문자열 형태로 추가합니다.

print(result)

고민하다가 풀이된걸 보고 이해했습니다. 풀이를 다시 써보면서 이해하는데 어려웠던 부분을 정리하는 차원에서 주석을 추가했습니다. 저같은 입문자분들께 도움이 되기를 바랍니다.

2017/03/10 18:27

cano

def stringCompress_rec(string):
    ans = ''
    count = 1
    string = string + '\0'
    for i in range(1, len(string)):
        if string[i - 1] == string[i]:
            count += 1
        else:
            ans += string[i - 1] + str(count) + stringCompress_rec(string[i:])
            break
    return ans

2014/12/08 23:26

투플러스

코드가 참 깔끔하고 알아보기가 쉽네요 - Shin gil sang, 2015/11/09 19:30
string = string + '\0' 이부분의 의미가 어떻게 되나요? - kim SeongHyeon, 2016/08/06 16:24
def compress_string(string)
  string.scan(/(\w)(\1*)/).map{|c, l| c + (l.size + 1).to_s}.join
end

지금 다시보니 gsub 만으로 해결할 수 있는 문제네요.

def compress_string(string)
  string.gsub(/((\w)\2*)/) { "#{$2}#{$1.size}"}
end

2014/12/10 22:26

Shim Won

R 인가요? - 예강효빠, 2017/05/27 02:51

언어는 자바입니다. 정규 표현식의 lookaround, capturing group 을 이용했습니다.

package rootcucu.codefight;


public class CharacterRepeat {
    public static void main(String[] args){
        CharacterRepeat obj = new CharacterRepeat();
        for (String a:"aabbbcccdd ####$$&&&&&&!! 귤귤귤감감배배배배".split(" "))
            System.out.println(a + "\n" + obj.compress(a) + "\n");
    }

    String compress(String s) {
        String t = "";
        for (String u : s.split("(?<=(.))(?!\\1)"))
            t = t + u.charAt(0) + u.length();
        return t;
    }

}

실행 결과입니다.

aabbbcccdd
a2b3c3d2

####$$&&&&&&!!
#4$2&6!2

귤귤귤감감배배배배
귤3감2배4

2015/05/08 13:12

rootcucu

죄송하지만 s.split("(?<=(.))(?!\\1)") 이부분에 대해서 자세히 설명해주실분 계신가요? ㅠㅠ 정규식을 잘 몰라서요 - 김재인, 2017/03/28 17:54
#include <stdio.h>
#include <string.h>
int main()
{
    int len;
    int count = 0;
    char arr[255];
    scanf("%s", arr);
    len = strlen(arr);
    for (int i = 0; i < len; i++)
    {
        count++;
        if (arr[i] != arr[i + 1])
        {
            printf("%c%d", arr[i], count);
            count = 0;
        }
    }

}

2016/12/06 17:59

박찬영

c로 풀이한 답중에 가장 명쾌한듯 .... 굿굿 - 김우진, 2017/04/16 16:14
import java.util.Scanner;

public class StringZip {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String data = sc.nextLine() + " ", anw = "";
        int count = 1;
        for (int i = 0; i < data.length() - 1; i++)
            if (data.charAt(i) == data.charAt(i + 1))
                count++;
            else {
                anw += data.charAt(i) + (count + "");
                count = 1;
            }
        System.out.println(anw);
    }
}

2018/05/31 19:05

김지훈

class String
  def compress
    self.chars.chunk{|e|e}.map{|e,a|[e,a.size]}.join
  end
end

루비 Enumerator를 체이닝해서 풀었습니다. 풀이 과정을 조금 풀어써보면, 아래와 같습니다.

"aaabbcccccca".compress
=> "a3b2c6a1"
"aaabbcccccca".chars
=> ["a", "a", "a", "b", "b", "c", "c", "c", "c", "c", "c", "a"]
"aaabbcccccca".chars.chunk{|e|e}.to_a
=> [["a", ["a", "a", "a"]], ["b", ["b", "b"]], ["c", ["c", "c", "c", "c", "c", "c"]], ["a", ["a"]]]
"aaabbcccccca".chars.chunk{|e|e}.map{|e,a|[e,a.size]}
=> [["a", 3], ["b", 2], ["c", 6], ["a", 1]]
"aaabbcccccca".chars.chunk{|e|e}.map{|e,a|[e,a.size]}.join
=> "a3b2c6a1"

2014/12/13 13:44

nacyot

        static void Main(string[] args)
        {
            string s = Console.ReadLine();
            for(int i = 0; i < s.Length;i++)
            {
                int count = 1;
                for (int x = i; x < s.Length-1; x++)
                {
                    if (s[x] == s[x + 1])
                    {
                        count++;
                    }
                    else
                    {
                        break;
                    }
                }
                i += count - 1;
                Console.Write(s[i] + count.ToString());
            }

        }

2015/09/24 20:53

정우진

a = str(input("압축할 문자열 입력 : ")) + chr(32)
b = ''
count = 1
for i in range(len(a) - 1):
    if a[i] == a[i + 1]:
        count += 1
    else:
        b += a[i] + str(count)
        count = 1
print(b)

공백문자를 사용하니까 코드가 꽤나 줄여지더군요.

2017/05/25 19:45

S ReolSt

i=input("문자열을 입력하십시오: ")
elst=[i[0]]
c=1
for n in range(len(i)-1):
    if i[n]==i[n+1]:
        c+=1
    else:
        elst.append(str(c))
        elst.append(i[n+1])
        c=1
elst.append(str(c))
print("".join(elst))

2020/01/19 19:42

박시원

훌륭하네요.. 난 왜 이렇게 생각못하남~~ - maluchi, 2020/02/10 22:31

그냥 C/C++ 언어 답게 풀었습니다. 쉬운 문제인데 이런 문제도 코딩 인터뷰에서 아주 자주 등장합니다.

#include <iostream>
#include <string>
#include <cassert>
#include <sstream>

std::string compress(const std::string &input) {
  if (input.length() == 0)
    return "";

  std::stringstream ss;
  char prev = input[0];
  int count = 0;
  for (auto c : input) {
    if (prev != c) {
      ss << prev << count;
      prev = c;
      count = 1;
    } else {
      ++count;
    }
  }
  ss << prev << count;
  return ss.str();
}

int main() {
  assert(compress("aaabbcccccca") == "a3b2c6a1");
}

2015/01/04 09:32

race.condition

펄입니다 저도 정규표현식으로 풀려고 했는데 이미 쓰신 분이 계셔서 ;;

perl -e 'my%check;for(split "",$ARGV[0]){$check{$_}++}for(keys %check){print $_,$check{$_}}'

2015/01/24 09:37

이병곤

풀이법이 다들 비슷해보이기에^^; 정규식을 이용하고 Java의 Pattern, Matcher 클래스를 활용했습니다.

public class StringCompressor {
    public String compress(String arg) {
        Pattern p = Pattern.compile("(\\w)(\\1*)");
        Matcher m = p.matcher(arg);
        StringBuilder result = new StringBuilder();
        while( m.find() ) {
            result.append( arg.charAt(m.start()) + "" + (m.end()-m.start()) );
        }
        return result.toString();
    }

    @Test
    public void test() {
        assertEquals("a3b2c6a1", new StringCompressor().compress("aaabbcccccca"));
    }
}

2015/03/10 23:59

이 승효

def comp(a):
     b=sorted(list(set(a)))
     result = ''
     for s in b:
          result += s
          result += str(a.count(s))
     return result




2015/12/23 14:24

창자.

+1 count를 하면 맨 뒤에 있는 'a'도 포함되서 카운트 되기 때문에 정답이 다르게 나옵니다. - Taesoo Kim, 2018/06/07 16:55
from itertools import *
while __name__ == '__main__':
    inpt = input('입력: ');s = ''
    for x, y in groupby(inpt):
        z = len(list(y))
        s = s+x
        if z>1:s = s+str(z)
    print(s)

짧게 줄이려고 했는데 y를 한번 호출하면 빈 리스트가 돼서 포기했습니다.... 파이썬 3.5.1입니다.

+추가: 시간이 지나고 보니 줄일 수 있더군요.

from itertools import groupby
while __name__ == '__main__':
    print(''.join(x + (lambda z: str(z) if z>1 else '')(len(list(y))) for x,y in groupby(input('입력: '))))

+줄바꿈 없음

list(print(''.join(x + (lambda z: str(z) if z>1 else '')(len(list(y))) for x,y in __import__('itertools').groupby(input('입력: ')))) for x in __import__('itertools').count())

+임포트 반복 제거

(lambda it: list(print(''.join(x + (lambda z: str(z) if z>1 else '')(len(list(y))) for x,y in it.groupby(input('입력: ')))) for x in it.count()))(__import__('itertools'))

2016/03/15 23:44

Flair Sizz

Python

import re

input_data = "aaabbcccccca"

filted = re.findall("(\\w)(\\1*)", input_data)

output = ""
for x, y in filted:
    output += x
    if not len(y) == 0:
        output += str(len(y) + 1)  

print(output)

2016/04/27 18:18

SanghoSeo

(한줄코드)Python 3.6, 자고 일어났더니 한결 좋아졌습니다.

import re, functools

functools.reduce(str.__add__, (y+str(len(x)) for x,y in re.findall(r"((\w)\2*)", 'aaabbcccccca')))

2017/05/27 02:00

예강효빠

javascript

var strzip = str => str.replace(/(\D)\1*/g, s => s[0] + s.length);

console.log(strzip("aaabbcccccca"));
console.log(strzip("abcdefg"));

2017/06/19 17:19

funnystyle

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

string compress_string(const string &in_str)
{
    int count = 0;
    char prev_char = in_str.at(0);
    stringstream ss;

    if(in_str.length() == 0)
        return "";

    for (auto c : in_str) {
        if (prev_char != c) {
            ss << prev_char << count;
            prev_char = c;
            count = 1;
        } else {
            ++count;
        }
    }
    ss << prev_char << count;
    return ss.str();
}


int main()
{
    string org_str = "";
    string compressed_str = "";

    getline(cin, org_str);

    compressed_str = compress_string(org_str);

    cout << compressed_str << endl;
}

2017/06/29 15:55

Logan

test = 'aaabbcccccca'
dic = {}

for i in range(len(test)):
  dic[test[i]] = 0
for i in range(len(test)):
  dic[test[i]] += 1

l = ''
for k,v in dic.items():
  l += k + str(v)

print(l)

2019/03/14 00:44

Gerrad kim

def stringCompressor(s):
    s += "\0"
    m = 0
    n = len(s)
    result = ""
    while 1:
        for i in range(m,len(s)):
            if s[m] != s[i]:
                n = i
                break
        result = result+s[m]+str(n-m)
        m = n
        if n == len(s)-1:
            break
        else:
            n = len(s)

    return result

2014/12/06 11:51

원 동건

clojure

(defn string-compress [s]
  (->> s
       (partition-by identity)
       (mapcat (fn [x] [(first x) (count x)]))
       (apply str)))

(string-compress "aaabbcccccca")
;=> "a3b2c6a1"

2014/12/06 18:29

김 은평

ExString = 'aaabbcccccca'
ResltList =[]
count = 1
index = 0

while 1:
    if index+1 is len(ExString):
        ResltList.append(ExString[index])
        ResltList.append(str(count)) 
        break
    elif ExString[index] is  ExString[index+1]:
        count += 1
        index += 1
        #print(count)
        #print(index)
    else:
        ResltList.append(ExString[index])
        ResltList.append(str(count)) 
        #print(ResltList)
        count =1
        index += 1
print(''.join(ResltList))

2014/12/09 21:34

kong byongsoo

python 2.7

def compress_string(s):
    _c = ""
    cnt = 0
    result = ""
    for c in s:
        if c!=_c:
            _c = c
            if cnt: result += str(cnt)
            result += c
            cnt = 1
        else:
            cnt +=1
    if cnt: result += str(cnt)
    return result

print compress_string("aaabbcccccca")

2014/12/11 13:06

pahkey

출력 결과가 "a3b2c6a"로 나옵니다. - race.condition, 2015/01/04 09:20
아.. 그러네요. 수정했습니다. 마지막 cnt값을 append하는것을 잊었네요. 알려주셔서 감사합니다. - pahkey, 2015/01/05 09:08

Scala

def compress(input: String): String = {
    def fn(head: Char, input: String, count: Int, result: List[String]): List[String] = {
        if(input == "") 
            s"$head$count" :: result
        else if(head == input.head) {
            fn(input.head, input.tail, count + 1, result)
        } else {
            fn(input.head, input.tail, 1, s"$head$count" :: result)
        }
    }

    fn(input.head, input.tail, 1, Nil).reverse.mkString
}

println(compress("aaabbcccccca"))

2014/12/15 11:05

killbirds

java로 풀었습니다

어휴~ 지저분하네요 ㅠㅠ 반성하겠습니다.

public class Test_465 {

    public String compress(String str){
        int cnt=0;
        char tmp=' ';
        String result="";
        for(int i=0;i<str.length();i++){
            if(tmp==' '){
                tmp=str.charAt(i);
                cnt++;
            }else if(tmp==str.charAt(i)){
                cnt++;
            }else{
                result+=tmp+String.valueOf(cnt);
                cnt=0;
                tmp=str.charAt(i);
                cnt++;
            }
            if(i==str.length()-1)
                result+=tmp+String.valueOf(cnt);
        }
        return result;
    }

    public static void main(String args[]){
        System.out.println(new Test_465().compress("aaabbddbbeebbbba"));
    }
}

2014/12/23 18:45

23king

Perl

perl -le"$_=<>;s/((\w)\2*)/$2.(length $1)/ge;print"

2015/01/02 17:23

*IDLE*

Scala

object StringCompresser extends App {
  def compress(s: String) = {
    def pairing(s: String): List[String] = {
      val (l, r) = s.span(_ == s(0))
      l :: (if (r == "") Nil else pairing(r))
    }
    pairing(s).map(x => "" + x(0) + x.length).reduce(_ + _)
  }

  println(compress("aaabbcccccca"))
}

2015/01/18 20:06

이 호연

coding by python beginner

import sys; t0 = sys.argv[1]
prev = rs = ''
dupCnt = 1
for i in range( len(t0) ):
    if t0[i] == prev:
        dupCnt +=1;
    elif prev != '':
        rs = rs + prev + str(dupCnt)
        dupCnt = 1;
    prev = t0[i]
    if i == len(t0)-1: rs = rs + prev + str(dupCnt)

print(rs)

2015/01/23 13:01

vegan

자바입니다.

import java.util.Scanner;

public class CompressString {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the Text : ");
        String input = sc.nextLine().trim();
        if("".equals(input)){
            System.out.println("the input is empty.");
        } else {
            System.out.println(CompressString.compress(input));
        }
        sc.close();
    }

    public static String compress(String text){
        char[] charArr = text.toCharArray();
        char prevChar=' ';
        StringBuffer sb= new StringBuffer();
        int charArrLength = charArr.length;
        int dupCnt=1;

        for(int i=0; i<charArrLength; i++){
            if(prevChar==charArr[i]){
                dupCnt++;
            } else {
                if(i!=0){ // 중복값에 대한 처리
                    sb.append(prevChar);
                    sb.append(dupCnt);
                }
                dupCnt=1;
            }
            prevChar = charArr[i];
            if(i==charArrLength-1){  // 마지막 값에 대한 처리
                sb.append(prevChar);
                sb.append(dupCnt);
            }           
        }

        return sb.toString();
    }

}

2015/01/24 22:19

mojo_kb

파이썬 2.7입니다.


str_in = raw_input("Enter string: ")

count = 0
compressed_str = []

for index in str_in:
    if count == 0:
        compressed_str.append(index)
        count += 1
    elif index == compressed_str[-1]:
        count += 1
    elif index != compressed_str[-1]:
        compressed_str.append(count)
        compressed_str.append(index)
        count = 1

compressed_str.append(count)

print reduce(lambda x,y: str(x)+str(y),compressed_str)

2015/01/26 20:42

SPJung

자바입니다.
다소 마음에 들지는 않네요. 첫값과 끝값 처리가 아쉽습니다.


public class Compress {
    public String compressString(String origin){
        if(origin == null || origin.length() == 0) return null;
        //첫 값 처리
        int count = 1;
        char oldChar = origin.charAt(0);
        char currentChar;
        StringBuffer sb = new StringBuffer();

        for(int i = 1; i < origin.length(); i++){
            currentChar = origin.charAt(i);
            if(currentChar == oldChar){
                count++;
            } else {
                sb.append(oldChar);
                sb.append(count);
                oldChar = currentChar;
                count = 1;

            }
        }
        //마지막 값 처리
        sb.append(oldChar);
        sb.append(count);
        return sb.toString();
    }
}


테스트 코드 입니다.

import static org.junit.Assert.*;

import org.junit.Test;


public class CompressTest
{
    @Test
    public void testCompressString(){
        String originStr = "aaabbcccccca";
        String expectedStr = "a3b2c6a1";
        Compress comp = new Compress();
        String actualStr = comp.compressString(originStr);
        System.out.println(actualStr);
        assertEquals(expectedStr, actualStr);

    }

}

2015/02/03 18:10

임 성현

import sys

def main():
    try:
        s = sys.argv[1]
        count = 1
        temp =''
        result=''

        for word in s:
            if temp == '':
                temp = s[0]
            elif temp != word:
                result += temp + str(count)
                temp = word
                count = 1
            else:
                count = count + 1
        result += temp + str(count)
        print(result)    

    except IndexError:
        print('Usage : python3 [compression.py] [string]')
if __name__ == '__main__':
  main()

2015/02/15 11:40

amainlog

package compress_string;

public class compressstring {

    public String compress(String str){
        String result = "";
        char temp = ' ';
        int count=0;

        for( int i=0; i<str.length(); i++ ){
            if( temp == ' ' ){
                temp = str.charAt(i);
                count = 1;
            }
            else if( temp == str.charAt(i) ){
                count++;
            }
            else{   //temp != str.charAt(i)
                result = result + temp + String.valueOf(count);
                temp = str.charAt(i);
                count = 1;
            }
            if( i>=str.length()-1 ){
                result = result + temp + String.valueOf(count);
            }
        }
        return result;
    }

    public static void main(String[] args){
        System.out.println(new compressstring().compress("aaabbcccccca"));
    }
}

2015/02/19 07:04

zerofury

Swift로 풀어보았습니다.

import Foundation

func partition(array: [String]) -> [[String]] {
  var result = [[String]]()
  var lastValue: String?

  for item in array {
    let value = item

    if value == lastValue {
      result[result.count-1].append(value)
    } else {
      result.append([value])
      lastValue = value
    }
  }
  return result
}

var x = partition(["a","a","c", "d", "b","b","b","b","c","c","c","c"])
  .map{ (item: [String]) -> String in
    let count = item.reduce(0){ (s0, s1) in s0 + 1 }
    let str = item.first! + String(count)
    return str
  }.reduce("") { $0 + $1 }

println("Result : \(x)")

2015/03/15 18:50

Ahn Jung Min

s = "aaabbcccccca"
r = ""
prev = s[0]
cnt=0
for c in s:
    if c == prev:
        cnt += 1
    else:
        r += prev + str(cnt)
        cnt=1
    prev = c
r += prev + str(cnt)
print(r)


2015/03/16 12:10

임 진승

Using python

#!/usr/bin/python

def chrComp(a):
    count = 0
    b = []
    for i in a:
        if count ==0:
            b.append(i)
            count += 1
        elif i == b[-1]:
            count += 1
        elif i != b[-1]:
            b.append(str(count))
            b.append(i)
            count = 1
    b.append(str(count))
    print "".join(b)

a = raw_input("input character list: ")
chrComp(a)

2015/03/29 21:20

freeefly

    private String test2(String s) {
        StringBuilder sb= new StringBuilder();
        int size = s.length();
        String lastText = "";
        int cnt = 0;
        for(int i=0; i<size; ++i ) {
            String tmp = s.substring(i, i+1);
            if("".equals( lastText )) {
                sb.append(tmp); cnt++;
                lastText = tmp;
            } else if(tmp.equals(lastText)){
                cnt++;
            } else {//카운트를 적고 초기화
                sb.append(String.valueOf(cnt));
                lastText = tmp; 
                sb.append(tmp); cnt = 1;
            }
            if(i == size-1) {
                sb.append(String.valueOf(cnt));
            }
        }
        return sb.toString();
    }

2015/04/12 12:06

김대원

c 언어입니다.

#include <stdio.h>
 int main(void)
 {
     int a = 0, b = 0, c = 0, d = 0, e = 0, arr[100];
     char str[100], str1[100];
     printf("문자열을 써라. 문자열을 압축시키겠다.");

     scanf("%s", &str);

     while(str[a - 1]!=0)
     {
        if(d==0)
        {
            str1[c] = str[a];
            d++;
        }
        else if(str[a]==str1[c])
        {
            b++;
            a++;
        }
        else if(str[a]!=str1[c])
        {
            arr[c] = b;
            b = 0;
            d = 0;
            c++;
        }
     }
     c = 0; 
     while(str1[c]!=0)
     {
        printf("%c", str1[c]);
        printf("%d",arr[c]);
        c++;
     }

     return 0;
 }

2015/04/21 15:47

전승빈

''.join(('%s%d' % k for k in reduce(lambda y, z: y[:-1] + [(z[0], y[-1][1] + 1)] if y[-1][0] == z[0] else y + [z], ((x, 1) for x in 'aaabbcccccca'), [('', 1)])[1:]))

python 2.7.6

2015/04/27 14:33

BangC

python 2.7입니다.

입력 문자를 매번 하나씩 뽑아서 이전꺼와 다르면 이전 문자와 그때까지 세었떤 Counter를 넣는 식으로 만들었습니다.

# -*- coding: utf-8 -*-
inputList = list(raw_input("문자를 입력 하세요 :"))
beforeString =inputList.pop(0)
stringCounter = 1
outputList =[]

for oneString in inputList:
    if beforeString != oneString:
        outputList.append(beforeString)
        outputList.append(str(stringCounter))
        beforeString = oneString
        stringCounter = 1
    else :
        stringCounter += 1
outputList.append(beforeString)
outputList.append(str(stringCounter))

print ''.join(outputList)

2015/05/01 02:38

kong byongsoo

Javascript 입니다.

var str = "aaabbccccccabccdd가나나다다ee다다다다다다라";
var beforeChar, innerCnt = 0, retStr = "";
for(var i=0;i<str.length+1;i++) {
    if(i > 0) {
        if(beforeChar === str[i]) {
            innerCnt += 1;
    } else {
        retStr += (beforeChar + String(innerCnt+1));
        innerCnt = 0;
    }
    }
    beforeChar = str[i];
}
console.log(retStr)

2015/05/06 15:11

JakartaKim

python으로 했어요 ㅎㅎ 다른 분들풀이 읽어보니깐 역시 고수분들이 많네요!

#465.py
inputs="aadfbaba"
ans=[]
count=1
print range(len(inputs)) 

for x in range(len(inputs)-1):

    if inputs[x]==inputs[x+1]:

        count+=1

    else :
        ans.append(inputs[x])
        ans.append(count)
        count=1
        x+=1
else : 
    ans.append(inputs[x])
    ans.append(count)

print ans 

2015/05/11 17:27

심재용

Java코드입니다.

간결하진않지만 갑자기 머리가돌아가서 짰는데 되긴하네요

public static void main(String[] args) {

      Scanner keyboard = new Scanner(System.in);
      String str;
      str = keyboard.nextLine() + " ";

      int temp = 1;

      char s; 
      String Final = "";

      for(int i = 0; i< str.length() - 1; i++){
          s = str.charAt(i);
          if (s == str.charAt(i+1)){
              temp++;
          } else {
              Final = Final + s + temp;
              temp = 1;
          }
      }
      System.out.println(Final);
}


2015/06/15 01:11

문성훈

C#으로 작성했습니다. StringBuild를 사용하여 algorithm을 개선했습니다. time complexity O(n) and space complexity O(n) 입니다.

using System.Text;

        public string PrintCompression(string input)
        {
            var count = 1;
            var last = input[0].ToString();
            var output = new StringBuilder();
            for (int i = 1; i < input.Length; i++)
            {
                if (input[i].ToString() != last)
                {
                    output.Append(last);
                    output.Append(count);
                    last = input[i].ToString();
                    count = 1;
                    continue;
                }
                count++;
            }
            output.Append(last);
            output.Append(count);
            return output.ToString();
        }

2015/06/18 16:14

Straß Böhm Jäger

static string Answer(string str)
        {
            int cnt = 1;
            string retrun = "";


            Stack<string> test = new Stack<string>();

            for (int i = str.Length - 1; i > 0; i--)
            {
                if (str[i] == str[i-1])
                {
                    cnt++;
                }
                else
                {
                    test.Push(str[i] + cnt.ToString());
                    cnt = 1;
                }

                if (i==1)
                {
                    test.Push(str[i - 1] + cnt.ToString());
                }
            }

            while (test.Count != 0)
            {
                retrun += test.Pop();
            }

            return retrun;
        }

2015/06/25 21:49

허 빈

#Compresses the string

def compress_string(s):
        """(str) -> str

        This functions receives a string and returns the compressed version.

        >>>compress_string("aaabbcccccca")
        a3b2c6a1
        """
        count = 0
        L = []
        for i in s:
                if count == 0:
                        L.append(i)
                        count = count + 1
                elif i == s[-1]:
                        count = count + 1
                elif i != s[-1]:
                        s.append(str(count))
                        s.append(i)
                        count = 1
        s.append(str(count))
        print "".join(s)

2015/06/28 21:06

Jethro

def compress(s):
  bfr = ""
  cnt = 0
  l = ""

  for c in s :
    if c==bfr : cnt+=1
    else:
      if (bfr!="") : l+=bfr+str(cnt)
      bfr=c
      cnt=1

  return l+bfr+str(cnt)

print compress("aaabbcccccca")

역시 거의 비슷한 풀이가 저 위에 있군요...

2015/07/09 14:20

Kim JungRae

package com.kang.test;



public class Sample1 {

    public void compress(String arg) {

        char[] c = arg.toCharArray();

        char buffC = c[0];
        int cnt = 1;
        String retStr = "";
        for (int i=0; i<c.length; i++){

            if(c[i] == buffC){
                cnt ++;

            }else{
                retStr  += buffC+""+cnt;
                buffC = c[i];
                cnt=1;
            }
        }
        retStr  += buffC+""+cnt;

        System.out.println(retStr);
    }


    public static void main(String[] args) {
        new Sample1().compress("aaabbccccccaa");
    }



}

2015/07/31 13:59

강 준영

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Input String :";

    string strInput;
    cin >> strInput;

    char chOri = strInput[0];
    int nNum = 1;

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

        if (chOri == strInput[i])
            nNum++;
        else
        {
            cout << chOri;

            chOri = strInput[i];

            if (nNum == 1)
                continue;

            cout << nNum;
            nNum = 1;
        }
    }

    cout << chOri;
    if (nNum != 1)
        cout << nNum;

    return 0;
}

2015/08/10 17:08

박 해수

static void exce72()
    {
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        int n = 0;
        char piv = '\0';

        for (int i = 0; i < str.length(); i++)
        {
            if (str.charAt(i) != piv)
            {
                if (i != 0)
                {
                    System.out.printf("%c%d", piv, n);
                }
                piv = str.charAt(i);
                n = 1;
            } else
                n++;
        }
        System.out.printf("%c%d", piv, n);
        scan.close();
    }

무난무난하게 풀어봤습니다.

2015/08/20 09:25

조서현

public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String value = br.readLine();

        char[] before = value.toCharArray();

        StringBuffer after = new StringBuffer();

        int number = 1;

        for (int i = 0; i < before.length; i++) {

            try {
                if (before[i] == before[i + 1]) {
                    number++;
                } else {
                    after.append("" + before[i]).append(number);
                    number = 1;
                }

            } catch (ArrayIndexOutOfBoundsException e) {
                if (number == 1)
                    after.append("" + before[i] + 1);
                else
                    after.append("" + before[i]).append(number);
            }
        }

        System.out.println(after);
    }

}

배열 범위 예외 처리 하느라 지저분해졌습니당

2015/09/14 15:14

임 찬혁

s="aaaaabbbaccccccc"

tem=""
count=0
re=""

for ch in s:
    print(ch)
    if ch !=tem:
        re+=(tem+str(count))
        tem=ch
        count=1
    else:
        count+=1
re+=tem+str(count)
re=re[1:]

2015/09/18 12:26

Graed

JAVA 초보입니다.

class Pressing{
    private char[] ch = null;
    private String result = "";

    public Pressing(){
        System.out.println("#코드도장 - 문자열압축");
        run();
    }

    private void run(){
        int cnt=1;

        System.out.print("입력 : ");
        Scanner sc = new Scanner(System.in);
        this.ch = sc.nextLine().toCharArray();

        for(int i=0; i<this.ch.length-1; i++){
            if(this.ch[i] == this.ch[i+1]){
                cnt++;
                if((i+1) == this.ch.length-1){  //마지막 인덱스 체크
                    this.result += Character.toString(this.ch[i]) + cnt;
                }
            }else{
                this.result += Character.toString(this.ch[i]) + cnt;
                cnt=1;
                if((i+1) == this.ch.length-1){  //마지막 인덱스 체크
                    this.result += Character.toString(this.ch[i+1]) + cnt;
                }
            }
        }
        System.out.println("결과 : " + result);
        sc.close();
    }
}

public class CodeDoZang {

    public static void main(String[] args) {
        // 문자열 압축하기
        new Pressing();
    }
}

2015/10/09 16:16

쏘르빈

파이썬입니다.

def char_zip(input_str):
    cnt = 0
    ziped_string = ""
    for i in input_str:
        if cnt == 0:    # 첫 문자 추가
            ziped_string += i
            cnt = 1
        elif i == ziped_string[-1]: # 이전 문자와 같을 경우 카운트 증가
            cnt += 1
        else:   # 이전 문자와 다를 경우 카운트를 문자열에 넣고 다음 문자를 넣는다
            ziped_string += str(cnt) + i
            cnt = 1
    ziped_string += str(cnt)    # 마지막 문자에 대한 카운트 넣기
    return ziped_string

print(char_zip("aaabbcccccca"))

2015/11/09 23:19

김경호

def string_compression(s):
    result = []
    prev = s[1]
    cnt = 1
    result.append([prev, cnt])

    for i in range(1, len(s)):
        curr = s[i]
        if prev == curr:
            cnt += 1
            result[len(result)-1] = [curr, cnt]
        else:
            cnt = 1
            result.append([curr, cnt])

        prev = s[i]

    compression_string = ""
    for result_element in result:
        compression_string = compression_string + "".join(str(x) for x in result_element)                

    return compression_string


print str(string_compression("aaabbcccccca"))

하고나서 다른 분들 코드를 보니 저는 아직 멀었네요. ㅎ

2015/11/13 15:51

파이썬공부하는학생

<?php 
    $input = 'aaabbcccccca';

    $output = '';
    $temp = 1;

    for($i=0;$i<strlen($input)+1;$i++) {
        if($i != 0) {
            if($input[$i] == $input[$i-1]) $temp++;
            else {
                $output .= $input[$i-1].$temp;
                $temp = 1;
            }
        }
    }

    echo $output;
?>

2015/11/19 15:02

한기우

#include <stdio.h>
#define N 100
int main(void){
        char arr[N];
        int i,a=1;
        printf("문자열을 입력하시오:");
        scanf("%s",arr);
        for(i=0;arr[i]!='\0';i++){
                if(arr[i]==arr[i+1]){
                        a++;
                }
                else{
                        printf("%c%d",arr[i],a);
                        a=1;
                }
                printf("\n");
        }
        return 0;
}

2015/12/31 11:25

김종헌

  • python으로 작성하였습니다.
#aaabbcccccca ->a3b2c6a1
s="aaabbcccccca"
o=[]
i=0
while (i<len(s)):
    if i==0 or o[-2]!=s[i]: #new character
        o.append(s[i]);o.append(1)
    else: #same character as prev
        o[-1]+=1       
    i+=1

print "".join(str(c) for c in o)

2016/01/08 09:10

씨니컬우기님

s = "aaabbcccccca" r = "" prev = s[0] cnt=0 for c in s: if c == prev: cnt += 1 else: r += prev + str(cnt) cnt=1 prev = c r += prev + str(cnt) print(r)

2016/01/12 11:59

Hitz

s='aaabbcccccca'
o=[]
for i in s:
    if len(o)>0 and o[-2]==i:o[-1]+=1
    else:o += [i,1]
o = ''.join([str(x) for x in o])
print o

2016/01/20 21:25

상파

#coding: CP949

text=input("문자를 입력해라:")
result=""
i=1
p=0
while i <= len(text)-1:
    if text[i] == text[i-1]:
        i+=1
    else:
        result+=eval("text[p]")+str(eval("i-p"))
        p=i
        i+=1
result+=eval("text[p]")+str(eval("i-p"))
print(result)

2016/02/25 18:16

lovegalois2

스위프트 문법 연습중.

var input = "aabbbcczzaaa"

var output : Array<Int> = Array<Int>(count: 26, repeatedValue: 0)

for char in input.characters{
    var num = String(char).lowercaseString.utf8.map{Int($0)}[0]

    num -= 97
    var count = output[num]
    count += 1
    output[num] = count
}

var first = 97
for i in output{

    if(i == 0){
        ++first
        continue
    }

    var c = String(UnicodeScalar(first))
    ++first
    print("\(c)\(output[i])")
}

2016/02/29 17:35

Ruby

compress = ->s{ s.gsub(/((\w)\2*)/){[$2,$1.size]*''} }

Test

expect(compress["aaabbcccccca"]).to eq "a3b2c6a1"

2016/03/01 07:02

rk

쪽팔리지만 -_ㅠ;; 자바 입니다

@Test
    public void t1() {
        String str = "aaaaabbbcccdddt";
        char[] a = str.toCharArray();
        int size = a.length;
        int k = 1;
        StringBuilder sb = new StringBuilder();

        for (int i = 1; i < size; i++) {

            if (a[i-1] == a[i]) {
                k++;
                if (i == size - 1) {
                    sb.append(a[i] + String.valueOf(k));
                }
            } else {
                if (i == size - 1) {
                    sb.append(a[i] + "1");
                } else {
                    sb.append(a[i] + String.valueOf(k));
                    k = 1;
                }
            }

        }
        System.out.println(sb.toString());

    }

2016/03/05 18:59

Hyunwoo Jeon

ArrayList<Character> compressString(String s) {
        int count = 1;
        ArrayList<Character> list = new ArrayList<Character>();

        for(int i=0; i<s.length()-1; i++) {
            if(s.charAt(i) == s.charAt(i+1)) {
                count++;
            }
            else {
                list.add(s.charAt(i));
                list.add((char)('0'+count));
                count = 1;
            }
        }
        list.add(s.charAt(s.length()-1));
        list.add((char)('0'+count));

        return list;
    }

java 코드

2016/03/16 02:04

mozzi

파이썬입니다. 억지로 짜냈습니다. 부끄럽지만 올립니다; Flair Sizz님의 itertools의 groupby()를 사용하면 훨씬 쉽게 풀수있네요. 감탄했습니다

def comp(src):
    i = 1
    temp = ''
    new = ''
    for x, y in enumerate(range(1, len(src))):
        if src[x] == src[y]:
            i += 1
            temp = src[x]
        else:
            new += temp
            new += str(i)
            i = 1
            temp = src[y]
    new += temp
    new += str(i)
    return new

src = 'aaabbcccccca'
print(comp(src))

2016/03/19 00:16

디디

groupby 함수를 가져다 썼습니다.

from itertools import groupby
def do(s):
    return ''.join(["{}{}".format(x, len(list(y))) for x, y in groupby(s)])

a = input()
print(do(a))

2016/03/22 18:19

룰루랄라

다른 좋은 방법들을 좀 보고 배워야겠네요 저는 그저 for문으로

StringBuffer result = new StringBuffer("");
        int count = 0 ;
        char ch = input.charAt(0);
        for(int i = 0 ; i < input.length() ;i++){
            if(ch == input.charAt(i)) {
                count++;
            }else{
                result.append(ch);
                if(count!=0)
                    result.append(count);
                ch = input.charAt(i);
                count  = 1;
            }
        }
        result.append(ch);
        if(count!= 0 )
          result.append(count);
        System.out.println(result.toString());
        return result.toString();

    }

2016/04/11 23:00

xeo

import re


str = input("입력")
ls=[]
dic={}

for i in range(len(str)):
    ls.append(str[i])


for i in range(len(ls)):
    number=0
    a=ls[i]
    for k in dic.keys():
        if a==k:
            continue
    for j in range(len(ls)):
        if a==ls[j]:
            number+=1
    dic[a]=number



print(dic)            




2016/04/17 22:18

gosemvhs1129

def stringCompress_rec(string): ans = '' count = 1 string = string + '\0' for i in range(1, len(string)): if string[i - 1] == string[i]: count += 1 else: ans += string[i - 1] + str(count) + stringCompress_rec(string[i:]) break return ans

2016/04/22 15:39

김수현

#파이썬3.4.2
s = input()
ans = []
count = 0
for i in s:
    new = i
    count += 1
    if count == 1:
        c = 1
    else:
        if new == old:
            c += 1
            if count == len(s):
                ans.append(str(new)+str(c))
        else:
            ans.append(str(old)+str(c))
            c = 1
            if count == len(s):
                ans.append(str(new)+str(c))
    old = i
print(''.join(ans))

2016/05/05 19:16

차우정

import re
import time
text=input()
t1=time.time()
count=1
i=0
result=""
l=len(text)
while i!=l:
    if len(text)==1:
        result=text+"1"
        break
    if text[i]==text[i+1]:
      count=count+1
      i=i+1
      if i==l-1:
          result=result+text[-1]+str(count)
          break
    else:
        result=result+text[i]+str(count)
        i=i+1
        count=1
        if i==l-1:
            result=result+text[-1]+"1"
            break
t2=time.time()
print(result,t2-t1)
t1=time.time()
p=re.compile(r"(\w)\1*")
result1=""
num2=p.finditer(text)
for i in num2:
    a=str(i.group())
    result1+=a[0]+str(len(a))
t2=time.time()
print(result1,t2-t1)

2016/05/08 22:55

Dr.Choi

그냥 비교하는 것과 정규식 비교 한번 써봤습니다. - Dr.Choi, 2016/05/08 23:43

갓 파이썬 배우기 시작한 뉴비입니다. 뉴비다운 평범한 방법으로 풀었습니당

def compress(string):

    res=''
    prev=string[0]
    count=0

    for ch in string:
        if prev!=ch:
            res=res+prev+str(count)
            count=1
        else:
            count+=1
        prev=ch
    res=res+prev+str(count)
    return res

string = raw_input("Enter string to compress : ")
print compress(string)



2016/05/14 20:17

정 덕

>>> from itertools import groupby
>>> "".join('%s%s' % (x, len(list(y))) for x, y in groupby('aaabbcccccca'))
'a3b2c6a1'

2016/05/31 21:20

Park Ohyoung

#파이썬2.7 입니다
#잘 돌아가네요 ㅠ

A = raw_input('문자를 입력:')
B = ""

i = 0
while A[i]:
    if A[i] == A[-1]:
        B += A[i] + str(len(A))
        break
    elif A[i+1] != A[i]:
        B += A[i] + str(i+1)
        A = A[i+1:]
        i = 0
    else:
        i += 1

print B

2016/06/01 11:35

최정진

#include <stdio.h>
/*
Solution: http://codingdojang.com/scode/465
*/
int main(){
    int i=0, j=0, cnt=0, length=0;
    char str[100];

    printf("Enter any string: ");
    scanf("%s", str);

    while(str[i] != '\0'){
        length++;
        i++;
    }

    for(i=0; i<=length; i++){
        if(str[j] == str[i]){
            cnt++;
        }
        else{
            printf("%c%d ", str[j], cnt);
            j=i;
            cnt=0;
            i--;
        }
    }

    return 0;
}

C로 해봤는데 뭔가 무식한 방법같네요;;

2016/06/01 23:48

luce

Java를 사용하였습니다.

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class StringCompress {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        byte[] array = str.getBytes(StandardCharsets.US_ASCII);
        int repeatCount = 1;

        System.out.print((char)array[0]);

        for (int i = 1; i < str.length(); i++) {
            if (array[i - 1] == array[i])
                repeatCount++;
            else {
                System.out.print(repeatCount);
                repeatCount = 1;
                System.out.print((char)array[i]);
            }
        }

        System.out.print(repeatCount);
        System.out.println();
    }
}

2016/06/04 14:49

손 량

Python 입니다.

#-*- coding: utf-8 -*-

def compress_string(inp):

    out = ""
    cnt = 1
    for idx in range(0, len(inp)):

        if idx == len(inp) - 1: #인덱스가 마지막에 와있다면
            out += inp[idx] + str(cnt)

        else:
            if inp[idx] == inp[idx+1]:
                cnt += 1
            else:
                out += inp[idx] + str(cnt)
                cnt = 1

    return out

print(compress_string("aaabbcccccca"))

2016/06/04 21:22

Park Byunglim

자바로 만들었습니다. 하 ...진짜 너무 더럽게 코딩을 해서 도움은 되지 못합니다.

package codingTest;

import java.util.Scanner;

public class Coding001 {

public static void main(String[] args) {

    Scanner scan=new Scanner(System.in);

    System.out.println("넣고 싶은 문자열 입력:");
    String put=scan.nextLine();
    String sum="";
    String sum2="";
    int count=1;



    for (int i = 0; i < put.length(); i++) {

        //처음에 1이 아니거나
        if(i>=1){
            //내 뒷수가 나랑 같으면 공통!
        if(put.charAt(i-1)==put.charAt(i)){ 
            //그럴때 카운트 ..
            count++;
            sum =put.charAt(i)+""+count;

        }       
        else{
            count=1; //초기화
            sum2 +=sum;
            sum="";

            try {
                //양옆에 수가 다르면 ...
                if(put.charAt(i-1)!=put.charAt(i)&&put.charAt(i)!=put.charAt(i+1)){
                    sum2 +=put.charAt(i)+""+1; //같은게 한개 ??
                }

            }

            //put.charAt(i+1) 자리가 없을때!
            catch (StringIndexOutOfBoundsException e) {
                sum2 +=put.charAt(i)+""+1;
            }

        }

        }


        //문자 하나만 입력할때.스트링 길이가 1일때!
        else if(1==put.length()){
            sum2=put.charAt(0)+""+1;
            break;
        }


        //마지막 i 번째에서 sum의 저장값을 sum2에 저장하고 끝내기.
        if(put.length()-1==i){
            sum2 +=sum;

        }


        //처음수가 다음수와 다를때.
        if(i==0){                       
            if(put.charAt(i)!=put.charAt(i+1)){                 
                sum2=put.charAt(i)+""+1;
            }
        }


    }

    //출력.
    System.out.println(sum2);


}

}

2016/06/06 21:58

정 성훈

파이썬 3.5

mun = input()

cnt = 0
mun_cnt = 1
while cnt < (len(mun) - 1):
    if mun[cnt] == mun[cnt+1]:
        mun_cnt += 1
        if cnt == (len(mun)-2):
            print(mun[cnt]+str(mun_cnt), end="")
    elif mun[cnt] != mun[cnt+1]:
        print(mun[cnt]+str(mun_cnt), end="")
        mun_cnt = 1
        if cnt == (len(mun)-2):
            print(mun[cnt+1]+str(mun_cnt), end="")        
    cnt += 1

항상 부족함을 느낍니다. 감사합니다.

2016/06/10 17:37

greatfarmer

package main

import "fmt"

func main() {
    s := "aaabbcccccca"
    result := []rune{}

    var r rune
    count := 0
    for _, v := range s {
        if r == v {
            count++
        } else {
            if (count != 0) {
                result = append(result, r, rune(count) + '0')
            }
            r = v
            count = 1
        }
    }
    result = append(result, r, rune(count)+'0')

    for _, v := range result {
        fmt.Printf("%c", v)
    }
}

2016/06/15 23:21

uuuuuup

package codingdojang.com;

import java.util.Scanner;

public class StringCompress {

public static void main(String[] args) 
{
    //문자열을 입력받아서
    Scanner scan = new Scanner( System.in );
    String your_String = new String( scan.nextLine() );
    //같은 문자가 연속적으로 반복되는 경우에
    //그 반복 횟수를 표시하여 문자열을 압축하기.

    //문자열의 길이 알고싶어.
    int your_StringLength = your_String.length();
    //문자들을 조립해야해요
    StringBuffer buffer = new StringBuffer("");

    int start = 0;          //비교 시작 문자
    int end = 0;            //비교 끝 문자
    int cnt = 1;            //같은 글자 갯수 
    char now_char = 'A';    //글자 저장 변수

    //문자를 탐색합니다.
    for( ; start < your_StringLength - 1; start = start + cnt )
    {
        //지금 index의 글자는 무슨 글자인가요?
        now_char = your_String.charAt( start );
        cnt = 1;                                //같은 글자는 1개서부터 시작
        end = start + 1;                        //비교 끝 문자는 시작문자 1개 다음 문자부터 비교
        boolean loop_butten = true;             //반복 지속

        while( loop_butten )
        {
            //실제 문자열의 길이는 your_StringLength - 1이지만,
            //비교는 your_Stringlength + 0까지 함으로 인해
            //indexException발생할 수 있다.
            //your_StringLength + 0까지 도달했다면
            //모둔 반복문을 탈출한다.

            //그럼? 저장해둔 문자와 갯수들은?
            //밑에서 나머지 작업을 실시한다.
            if( end == your_StringLength )
            {
                break;
            }
            if( now_char == your_String.charAt( end ) )
            {
                //같아요
                cnt++;                          //같은 글자 개수 ++1
                end++;                          //비교 끝 문자 1개 다음꺼로 이동
            }//if
            else
            {
                //틀려요
                buffer.append( now_char );      //buffer에 글자 저장
                buffer.append( cnt );           //buffer에 갯수도 저장

                loop_butten = false;            //반복문 탈출
            }//else 
        }//while_loop_butten 
    }//for_i

    //조립안하고 나왔으니 마저 하고..
    buffer.append( now_char );
    buffer.append( cnt );

    //출력 ~~ 
    System.out.println( buffer );
}

}

2016/07/09 16:36

박찬하


public class test {
    public static void main(String[] argv) {
        String str = "aaabbcccccca";
        String result = "";
        String preStr = "";
        String nextStr = "";

        int count = 0;

        for(int i =0 ; i<=str.length(); i++){
            if(i == str.length()){
                nextStr = str.substring(i);
            }else{
                nextStr = str.substring(i, i+1);    
            }

            if(nextStr.equals(preStr)){
                count++;
            }else{
                if(!preStr.equals("")){
                    result = result + preStr + String.valueOf(count+1);
                    count = 0;  
                }
            }

            preStr = nextStr;
        }

        System.out.println(str);
        System.out.println(result);
    }

}



2016/07/11 17:54

이 승준

s=input('압축할 문자열 : ')
k=0
while s[k:]!='':
    if k+1>=len(s):
        break
    if s[k]!=s[k+1]:
        s=s[:k+1]+'/'+s[k+1:]
        k+=2
    else:
        k+=1
s=s.split('/')

converted=''
for k in range(len(s)):
    converted+=s[k][0]+str(len(s[k]))
print(converted)

2016/07/18 21:49

최승호

a=list("귤귤귤감감배배배배")
a_length=len(a)
b=[]
stk=1
while 1 :
    if a_length > 1 :
        if a[0] == a[1] : 
            a.remove(a[0])
            stk+=1
            a_length-=1
            continue
        elif a[0] != a[1] : 
            b=b+[a[0]]+["%d"%stk]
            a.remove(a[0])
            stk=1
            a_length-=1
            continue
    b=b+[a[0]]+["%d"%stk]
    break
for i in b:
    print(i,end="")

python 3.5.2

2016/07/25 13:24

Zee

자바로 코딩

    public static void main(String[] args){

        // 문자열을 입력받아서, 같은 문자가 연속적으로 반복되는 경우에 그 반복 횟수를 표시하여 문자열을 압축하기.
        // 입력 예시: aaabbcccccca
        // 출력 예시: a3b2c6a1

        String text = "aaabbcccccca";

        int temp = 1;
        String str = "";

        for(int i=0; i<text.length()-1; i++){

            char ch = text.charAt(i);

            if( ch == text.charAt(i+1) ){
                temp++;
            }else{
                str = str + ch + temp;
                temp = 1;
            }
        } // for

        System.out.println("str :: ==> " + str);

    } // main

2016/07/26 14:33

황 정석

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("입-력");
        String str = sc.nextLine();
        int count=0;
        String temp="",result="";

        for(int i=0; i<str.length(); i++){
            if(temp==""){
                temp=str.substring(i,i+1);
                count++;
            }else if(temp.equals(str.substring(i,i+1))){//문자열이 연속되어있다면
                count++;
            }else{//문자열이 연속되어지지 않는다면
                result+=temp+count;
                count=0;
                temp=str.substring(i,i+1);
                count++;
            }if(i==str.length()-1){
                result +=temp+count;
            }
        }
        System.out.println(result);

    }

2016/08/01 15:29

Oh Tae Gyeoung

늅늅입니다. 자바로 풀어 봤습니다. 같은 문자가 2개 이상 반복되지 않으면 압축의 의미가 없기에, 카운트가 1일땐 글자를 그대로 표시하도록 만들었습니다. 16.08.03 (버그가 있었네요.)

public static String result = "";

    public static void main(String args[])
    {
        result = ZipString("aaaaaabbbbcccddefagedaaa");
        System.out.println(result);
    }

    public static String ZipString(String string)
    {
        String value = "";
        char indexer = string.charAt(0);
        int count =  0;

        for(int i = 0; i < string.length(); i++)
        {
            if(indexer == string.charAt(i))
            {
                count++;
                if(i < string.length()-1) 
                    continue;
            }

                value += indexer;

                if(count != 1)
                    value += count;

                count = 1;

                indexer = string.charAt(i);

        }
        return value;
    }

버그수정 결과 : a6b4c3d2efageda3 이렇게 출력됩니다.

2016/08/02 14:32

여우와향신료

문제를 보면, 문자가 하나만 있는 경우에는 숫자 1을 표시하도록 되어 있습니다. if (count!= 1) 부분은 없어야 될것 같습니다. - Kim Sean, 2016/09/06 09:17

Python

inputString = "aaabbcccccca"
newWord = inputString[0] + "1"
cnt = 1
for i in range(1,len(inputString)):
    if inputString[i] == inputString[i-1]:
        cnt += 1
        newWord = newWord[:-1] + str(cnt)
    else:
        cnt = 1
        newWord = newWord + inputString[i] + "1"
print newWord

2016/08/05 12:17

kim

python 3.5 (\w)(\1*) 동일한 문자반복에 대한 정규식 사용했습니다~

import re
print(''.join(x[0]+str(x[1].count(x[0])+1) for x in re.findall(r"(\w)(\1*)", r'abbbccccddddd')))

2016/08/16 00:12

정 우순

python 2.7

def StringCompress(s):
    count = 0
    index = 0
    s+='\0'
    answer = ""
    while(index+count<len(s)):
        if(s[index]==s[index+count]):
            count+=1
        else:
            answer+=str(s[index])+str(count)
            index+=count
            count=0

    print answer  

2016/08/25 21:25

leye195

exStr = input("문자열을 입력하세요 : ")
arr = { one : exStr.count(one) for one in set(exStr) }
print(arr)

2016/08/30 16:27

박창석

s=input()
string=""
s+='\0'
count=1
for i in range(len(s)-1):
    if s[i]==s[i+1]:
        count+=1
    else:
        string+=s[i]+str(count)
        count=1
print(string)

2016/09/03 11:36

정석철

python 2.7.1

내장함수, 정규식 등을 사용하지 않은 순수 알고리즘만 적용했습니다.

t,s,cnt='','',0
for c in "aaabbcccccca":
    if t!='' and t!=c:s,cnt,cnt=s+t+str(cnt),cnt,0
    cnt,t=cnt+1,c
print s+t+str(cnt)

result

a3b2c6a1

2016/09/04 18:34

happygrammer

def compressData(input):
    curData = input[0] #get first char
    currentCompressNumber = 1
    output = ""
    for i in range(1, len(input)):        
        if curData == input[i]: #get every single char
            currentCompressNumber += 1
        else: #update compressed output
            output += curData + str(currentCompressNumber)
            curData = input[i]                        
            currentCompressNumber = 1

    #add exception case for last single char or only one char
    if currentCompressNumber == 1:
        output += curData + str(currentCompressNumber)

    return output

print(compressData('a'))
print(compressData('ab'))
print(compressData('aaabbcccccca'))
print(compressData('aaabbccccccabcd'))

다른분들은 코드를 참 짧게 잘 만드시네요...^^;;;

2016/09/06 08:53

Kim Sean

import re
inputs='aaabbbcccccca'

print(re.sub(r"(\w)\1*",lambda match:str(match.group()[0])+str(len(str(match.group()))),inputs))

2016/09/09 16:45

kimchi soup

PHP로 했습니다. 배열에 넣고 처리해봤어요.

$input = "aaabbcccccca";

$result = array();
$input .= ' '; // Padding for last loop
for($i=0; $i<strlen($input); $i++) {
    if(array_key_exists($input[$i], $tmp_array)) {
        $tmp_array[$input[$i]]+=1;
    } else {
        if($tmp_array) {
            $result[]=$tmp_array;
            $tmp_array = array();
        }
        $tmp_array[$input[$i]]=1;
    }   
}

foreach($result as $r) {
    foreach($r as $k=>$v) {
        echo $k.$v;
    }
}

2016/09/21 08:22

허큐리

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
    char save_data[100];
    char comparing_data[] = "abcdefghijklnmopqrstuvwxyz";
    int counting_data[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
    int i, j;
    int save_data_len = 0;
    printf("put in the sentense with english not for another ");
    scanf_s("%s", &save_data, 100);
    save_data_len = strlen(save_data);
    for (i = 0; i <= save_data_len; i++)
    {
        j = 0;
        for (; j < sizeof(counting_data) / sizeof(int); j++)
            if (save_data[i] == comparing_data[j])
                counting_data[j] = counting_data[j] + 1;
        if (save_data == NULL)
            break;
    }
    i = 0;
    for (;i < sizeof(counting_data) / sizeof(int); i++)
    {
        if (counting_data[i] > 0)
        {
            printf("%c%d \n", comparing_data[i], counting_data[i]);
        }
    }
    system("pause");
}

2016/09/21 17:01

Joohyun Son

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char string_arr[1000];
    int arrLen = 0;
    int i;
    int count = 0;
    char tok;

    scanf("%s", string_arr);

    arrLen = strlen(string_arr);

    for(i = 0; i < arrLen ; i++)
    {   
        tok = string_arr[i];

        if(string_arr[i+1] == tok)
        {
            count++;
        }

        if(string_arr[i+1] != tok)
        {
            printf("%c%d", tok, count+1);
            tok = string_arr[i+1];
            count = 0;
        }
    }
}

2016/09/30 22:46

도장 코딩

#define _CRT_SECURE_NO_WARNINGS

#include <windows.h>
#include <stdio.h>

#define STR_LEN 100

int main(void) {
    char str[STR_LEN];
    char rst[STR_LEN] = { 0, };

    int j = 0;
    int num = 1;

    printf("input : ");
    gets_s(str);

    for (int i = 0; i < (int)strlen(str); i++) {
        if (!strncmp(str + i, str + i + 1, 1)) {
            num++;
        }
        else{
            strncpy(rst + j, str + i, 1);
            j++;
            _itoa(num, rst + j, 10);
            j++;
            num = 1;
        }
    }
    printf("output : %s", rst);

    system("pause");
    return 0;
}

2016/10/05 15:59

개허접

java

public static void main(String[] args)
{
    System.out.print("입력 : ");

    Scanner scanner = new Scanner(System.in);
    String n = scanner.next();              
    char[] as = n.toCharArray();            
    int cnt = 1;

    for(int i=0; i<as.length-1; i++)
    {           
        if(as[i] == as[i+1])
        {
            cnt++;              
        }
        if((as[i] != as[i+1]) ||(i==as.length - 2))
        {               
            System.out.print(as[i]);
            System.out.print(cnt);              
            cnt =1;                 
        }                   
    }       
}

}

2016/10/06 02:41

신 동땡

파이썬

strInput = input()
strInput = strInput + '\0'

strResult =strInput[0]
sum = 1

for i in range(1, len(strInput)):

    if strInput[i-1] == strInput[i]:
        sum += 1
    else:
        if sum > 1:
            strResult = strResult + str(sum) + strInput[i] 
            sum = 1
        elif sum == 1:
            strResult += strInput[i]

print(strResult)

2016/10/17 15:30

훠니

Python 코드입니다.

long = input()
short = ""

for i in range(len(long)):
    tmp = 0
    if (i != 0) and (long[i] == long[i-1]): continue
    else:
        for j in long[i:]:
            if long[i] == j:
                tmp += 1
                last = tmp
            else:
                short += "{}{}".format(long[i],tmp)
                break
short += "{}{}".format(long[i],last)
print(short)

last부분은 코드가 마지막 문자열을 처리해주지못해서 임시방편으로 썼는데 위에 투플러스님의 답안을 보고 아래와 같이 수정할 수 있었습니다.

long = input() + '\0'
short = ""

for i in range(len(long)):
    tmp = 0
    if (i != 0) and (long[i] == long[i-1]): continue
    else:
        for j in long[i:]:
            if long[i] == j:
                tmp += 1
            else:
                short += "{}{}".format(long[i],tmp)
                break
print(short)

파이썬 초보입니다. 많은 피드백 부탁드립니다!

2016/10/19 16:21

조 우성

안녕하세요. C++로 풀었습니다.

#include<iostream>
#include<string>
using namespace std;


void main()
{
    cout<<"Hello Stranger??"<<endl;

    int cnt = 0;

    string str = "aaabbcccccca";
    char pre = str[0];

    for(int i=0; i<str.length()+1; i++)
    {
        if(pre == str[i])
            cnt++;
        else
        {
            cout<<pre<<cnt;
            pre = str[i];
            cnt = 1;
        }
    }

}


2016/11/02 00:54

이재웅

앞뒤 비교해서 다르면 sb에 넣고 카운트 초기화

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class CompressString {

    public static void main(String[] args) {
    }

    public String compress(String string) {
        if(string.equals("") || string == null) 
            return null;

        StringBuffer sb = new StringBuffer();

        int count = 1;

        for(int i = 1; i < string.length(); i ++) {
            if(string.charAt(i) == string.charAt(i - 1))
                count++;
            else {
                sb.append(String.valueOf(string.charAt(i - 1)) + count + "");
                count = 1;              
            }

            if(i == string.length() - 1) {
                sb.append(String.valueOf(string.charAt(i)) + count + "");
                count = 1;
            }
        }

        return sb.toString();
    }

    @Test
    public void testCompress() {
        String string = "aaabbcccccca";
        String expected = "a3b2c6a1";

        assertEquals(expected, compress(string));
    }
}

2016/11/04 14:47

한비타

public static void main(String[] args) {
        String inputString = "aaabbcccccca"+';';
        String result = "";

        String curChar = inputString.charAt(0)+"";
        int count = 1;
        for(int i = 1; i < inputString.length();i++){
            if(curChar.equals(inputString.charAt(i)+"") ){
                count++;
            }else{
                result+=curChar+count;
                count = 1;
                curChar = inputString.charAt(i)+"";
            }
        }

        System.out.println(result);

    }

2016/11/14 21:46

wishwisdom

import re
d = input("문자열 입력 : ")
print(d + ":" + re.sub(r'(.)(\1*)', lambda m:m.group(1) + (str(m.group(2).count(m.group(1)) + 1) if m.group(2) else '1'), d))

Python 3.5.2에서 작성하였습니다.

2016/11/23 11:15

Yeo HyungGoo

string = input('? ')
backup = string[0]
n=1
for a in string[1:]:
    if a == backup:
        n +=1
    else:
        print(backup+str(n), end='')
        backup = a
        n = 1

2016/11/24 00:36

Makery

            string Input = "★★※★★";
            List<char> C = Input.ToCharArray().ToList<char>();
            int cnt;
            Char tmp;
            String ANS = "";

            while (C.Count!=0)
            {
                tmp = C.First();
                cnt = 0;
                while(C.Count!=0&&tmp==C.First())
                {
                    cnt++;
                    tmp = C.First();
                    C.RemoveAt(0);
                }
                ANS += tmp.ToString() + cnt;
            }
            //ANS = ★2※1★2

2016/11/26 23:05

Choco

num = input("임의의 문자를 입력해주세요 : ")
list_num = list(num)
set_num = set(list_num)

for i in set_num:
    a=list_num.count(i)
    print(i+str(a),end="")



2016/12/02 19:25

Kim Da Seul

Haskell

Prelude> let comp [] = []; comp (x:xs) = [x] ++ show (1+length h) ++ comp t where (h,t) = span(==x)xs
Prelude> comp "12"
"1121"
Prelude> comp "aabbcc"
"a2b2c2"
Prelude> 

2016/12/07 12:19

Han Jooyung

include

include

int main() { char str[256]; char curr; int i, cnt = 0;

fgets(str, sizeof(str), stdin);
curr = str[0];

for (i = 0; i < strlen(str); i++) {
    if (curr == str[i]) cnt++;
    else {
        printf("%c%d", curr, cnt);
        curr = str[i];
        cnt = 1;
    }
}
printf("\n");

return 0;

}

2016/12/07 23:52

리코둔

string = input()
count = 1
for x in range(len(string)-1): 
    if string[x] == string[x+1]:
        count += 1
    else:
        print(string[x],count,sep='',end='')
        count = 1
    if x == len(string)-2:
        print(string[x+1],count,sep='',end='')

#### 2016.12.11 D-438 ####

2016/12/11 23:40

GunBang

import java.util.*;
import java.io.*;

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int cnt =1;
        int len = s.length()-2;
        StringBuilder sb = new StringBuilder();

        for(int i=0; i<=len; i++) {
            char w = s.charAt(i);

            if(w == s.charAt(i+1)){
                cnt+=1;
            }

            else{
                sb.append(w+""+cnt);
                cnt = 1;
            }
            if(i == len){
                sb.append(w+""+cnt);
            }
        }
     System.out.println(sb);
    }
}

2016/12/16 19:59

박소정

problem1.py

a = list(input("입력 : "))

count=0 word = a[0]

for i in range(0,len(a)):

if word == a[i]:
    count += 1

    if i == len(a) - 1:
        print(word + str(count), end=' ')
        exit(-1)

else:
    print(word + str(count), end='')
    word = a[i]
    count = 1
    if i == len(a) - 1:
        print(word + str(count), end=' ')
        exit(-1)

2016/12/21 11:40

최 영훈

/*
1차원의 점들이 주어졌을 때, 그 중 가장 거리가 짧은 것의 쌍을 출력하는 함수를 작성하시오. 
(단 점들의 배열은 모두 정렬되어있다고 가정한다.)

예를들어 S={1, 3, 4, 8, 13, 17, 20} 이 주어졌다면, 결과값은 (3, 4)가 될 것이다.
 */


public class Algorithm5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] nS = {1, 3, 4, 8, 13, 17, 20};
        int[] nTotal = new int[2];

        int nTemp = 0, nMin = 999;

        for(int i = 1; i < nS.length; i++) {
            nTemp = nS[i] - nS[i-1];

            if(nTemp < nMin) {
                nMin = nTemp;
                nTotal[0] = nS[i-1];
                nTotal[1] = nS[i];
            }   // end if
        }   // end for

        System.out.println("가장 거리가 짧은 것은 :" + nTotal[0] + ", " + nTotal[1] + "입니다.");
    }

}

2016/12/26 13:34

김성곤

public class Lv1_02 {
    public static void main(String[] args) {
        StrAlzip s = new StrAlzip();
        s.play();
    }
}

class StrAlzip {
    private String str;

    public StrAlzip() {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        this.str = str+" ";     // for문에 필요한 조건을 위해 공백을 하나 더함
    }

    void play(){
        int count = 1;

        for (int i = 1; i < str.length(); i++) {
                if (str.charAt(i-1)==str.charAt(i)) {
                    count++;
                }else if (str.charAt(i-1)!=str.charAt(i)) {
                    System.out.print(str.charAt(i-1));
                    System.out.print(count);
                    count = 1;
                }
        }
    }
}

2016/12/26 18:15

bbubbush


#python 2.7x

stack = list('aaabbccccccaaabbccddaab'[::-1])
before,cnt,result = stack[-1],0,''
while stack:
    new = stack.pop()
    if before == new:
        cnt += 1
    else:
        result += "{}{}".format(before,cnt)
        before,cnt = new,1
result += "{}{}".format(new,cnt)
print result

파이썬2.7을 사용하였습니다. 스택을 이용했습니다 :P

2016/12/30 03:57

Daniel

import java.util.Scanner;

public class test04 { public static void main(String[] args) {

    String str;
    int cnt = 1;

    Scanner sc = new Scanner(System.in);
    System.out.print("문자를 입력하세요 : ");
    str = sc.nextLine();

    char[] ch = str.toCharArray();
    for(int i = 0 ; i <= str.length()-1; i++){

        if(str.length()-1 > i){
            if(ch[i] == ch[i+1]){
                cnt++;
            }else{
                System.out.print(ch[i] + "" + cnt);
                cnt = 1;
            }
        }else{
            System.out.print(ch[i] + "" + cnt);
        }
    }
}

}

2016/12/31 18:59

Min Daehong

이렇게 풀어도 되는지 모르겠지만...코알못이라 대충 풀어봤습니다.

#include <iostream>
using namespace std;
#define MAX 256


int main()
{
    char cInput[MAX];
    int  iLength = 0;
    int iCnt = 0;

    cin >> cInput;

    iLength = strlen(cInput);

    char cCheck = cInput[0];


    for(int i = 0; i < iLength; ++i)
    {
        if(cCheck == cInput[i])
            ++iCnt;

        else
        {
            cout << cCheck << iCnt;
            iCnt = 0;

            cCheck = cInput[i];
            ++iCnt;
        }
    }
    cout << cCheck << iCnt;

    return 0;
}


2017/01/06 00:57

이 학준


public class StringComp {
    public static void main(String[] args) {
        String input = "aaabbcccccca";
        int length = input.length();
        char[] output = new char[length*2];
        int outputIndex = 0;
        int outputNum = 0;
        for (int i=0; i<length; i++) {
            if (i == 0) {
                outputIndex = 0;
                output[outputIndex] = input.charAt(i);
                outputNum = 1;
            }
            else {
                if (input.charAt(i) == input.charAt(i-1)) { 
                    outputNum++;
                }
                else {
                    outputIndex = outputIndex + 2;
                    output[outputIndex] = input.charAt(i);
                    outputNum = 1;
                }
            }
            output[outputIndex+1] = Character.forDigit(outputNum, 10);
        }
        for (int i=0; i<outputIndex+2; i++) {
            System.out.print(output[i]);
        }
    }
}

2017/01/08 17:45

Choi Hyoje

import java.util.Scanner;

public class StringComp {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.next()+" ";
        int rep=1;
        StringBuffer res=new StringBuffer();
        for(int i=0;i<str.length()-1;i++){
            if(str.charAt(i) == str.charAt(i+1)){
                rep+=1;
            } else {
                res.append(str.charAt(i));
                res.append(rep);
                rep=1;
            }
        }
        System.out.println(res);
        sc.close();
    }
}

2017/01/11 22:52

바바

// C++ 현재 문자가 다음 문자와 다를때만 출력.. 글자가 버퍼 - 1 보다 작아야 함.. 에러 처리 생략..

int main()
{
    char acBuff[ 10000 ]  = { 0, };

    cin >> acBuff;

    int nCount = 0;

    for( unsigned int x = 0 ; x < strlen( acBuff ) ; ++x )
    {
        ++nCount;

        if( acBuff[ x ] != acBuff[ x + 1 ] )
        {
            cout << acBuff[ x ] << nCount;

            nCount = 0;
        } 
    }

    return 0;
}

2017/01/13 19:39

정 훈희

python 2.7

A = 'aaabbcccccca'
char = A[0]
n = 0
c= 1
new = []

for n in range(len(A)-1):
    if A[n] == A[n+1]:
        c += 1
    else:
        new += char+str(c)
        char = A[n+1]
        c = 1
        if n+1 == len(A)-1:
            new += char + str(c)

print ''.join(new)

결과 : a3b2c6a1

2017/02/02 20:32

조현우

#include <stdio.h>
#pragma warning(disable:4996)
void zip(char *arr) {
    for (int i = 0; arr[i] != NULL; i++) {
        int k = 1;
        printf("%c", arr[i]);
        if (arr[i + 1] == arr[i]) {
            for (int j = i; arr[j + 1] == arr[j]; j++) {
                k++;
            }

            i = i + k-1;
        }
        printf("%d", k);
    }
}
int main(void) {
    char arr[100];
    scanf("%s", arr);
    zip(arr);
}

2017/02/03 18:31

도야지

public class TextZip {
    public static void main(String[] args) {

        String text = "aaabbcccccca";
        String result = textZip(text);      
        System.out.println("text : " + text);
        System.out.println("result : " + result);
    }

    private static String textZip(String text) {

        char preText = text.charAt(0);
        int tempCount = 1;
        String result = "";

        for (int i = 1; i < text.length(); i++) {
            if (preText == text.charAt(i)) {
                tempCount ++;
            } else {
                result += Character.toString(preText) + tempCount;
                preText = text.charAt(i);
                tempCount = 1;
            }
        }       
        result += Character.toString(preText) + tempCount;

        return result;
    }
}

2017/02/09 22:50

김경수

def compact(data):
    result=data[0]
    n=1
    for i in range(1,len(data)):
        if result[-1]==data[i]:
            n+=1
        else:
            result+=str(n)+data[i]
            n=1
    result+=str(n)
    return result

2017/02/14 00:35

김구경

#include <stdio.h>
#include <string.h>
void main() {
    char str[] ="aaabbcccccca";
    int count = 1;

    for(int i=0;i<strlen(str);i++) {
        if(str[i+1]==str[i])
            count++;
        else {
            printf("%c%d", str[i], count);
            count=1;
        }
    }
}

2017/02/15 16:36

코딩초보

/*

dev : peanutBro

date : 170218

content :

문자열을 입력받아서, 같은 문자가 연속적으로 반복되는 경우에 그 반복 횟수를 표시하여 문자열을 압축하기.

입력 예시: aaabbcccccca

출력 예시: a3b2c6a1

*/

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <iostream>
#include <string>
using namespace std;



int main(void)
{
    string inputStr, resultStr="";
    char c = '0';
    int sameCount = 0;

    cout << "문자열을 입력하세요 : ";
    cin >> inputStr;

    for (int i = 0; i < inputStr.length(); i++)
    {
        if (c == '0')
        {
            c = inputStr[i];
            sameCount++;
            char* temp = new char[2];
            temp[0] = c;
            temp[1] = '\0';
            resultStr.append(temp);
            delete[] temp;
        }
        else
        {
            if (c == inputStr[i])
            {
                sameCount++;
            }
            else
            {
                char buff[100]; 
                _itoa(sameCount, buff, 10);
                resultStr.append(buff);
                sameCount = 0;
                c = '0';
                i--;
            }
        }

    }

    char buff[100];
    _itoa(sameCount, buff, 10);
    resultStr.append(buff);

    cout << resultStr;
}

2017/02/18 14:07

강병구 (peanutBro)

python 3.5.2

answer is 'a3b2c6a1'

마지막 string 에 대한 count부분이 어색(?)합니다. 별도 함수로 분리하려고 해봤는데 잘 안되서 부족하지만 answer_str 을 global 변수로 선언해서 동작하는 버전으로 올립니다.

L='aaabbcccccca'
temp_char = L[:1]
temp_str = ''
answer_str = ''
char_count = 0

def str_count(temp_char) :
    global answer_str
    char_count = temp_str.count(temp_char)
    answer_str += temp_char
    answer_str += str(char_count)        

for x in L :
    if (temp_char == x) :
        temp_str += x
    else :
        str_count(temp_char)
        temp_char = x
        temp_str= x

str_count(temp_char)

print(answer_str)

2017/02/21 17:17

강정민

public class StringCompression {

    public static void main(String[] args) {
        String s[] = "aaabbcccccca".split("");
        StringBuffer r = new StringBuffer();
        Integer c = 1;
        String b = s[0];
        r.append(s[0]);
        for (int i = 1; i < s.length; i++) {
            System.out.println(s[i] + " " + b);
            if (s[i].equals(b)) {
                c++;
            } else {
                r.append(c);
                r.append(s[i]);
                c = 1;
                b = s[i];
            }
            if(i == s.length-1) {
                r.append(c);
            }
        }
        System.out.println(r);
    }
}

2017/02/24 13:07

genius.choi

string = "aaabbccccca"
count = 0
result = ""
temp = ""

length = len(string)
if length > 0:
    count = 1
    result = string[0]

for at in range(1,length):
    temp = string[at]
    if temp == string[at-1]:
        count += 1
    else:
        result = result + str(count) + temp
        count = 1

print(result + str(count))

2017/02/24 14:44

Scott.Jun

import java.util.Scanner;

public class Pressure {

    /*
     * 문자열을 입력받아서, 같은 문자가 연속적으로 반복되는 경우에 그 반복 횟수를 표시하여 문자열을 압축하기. 입력 예시:
     * aaabbcccccca 출력 예시: a3b2c6a1
     */

    public static void output(String message) {

        String newString = "";
        int count = 1;
        char tempChar = message.charAt(0);
        for (int i = 1; i <= message.length() - 1; i++) {
            char indexChar = message.charAt(i);

            if (tempChar == indexChar) {
                count++;
            } else {
                newString += String.valueOf(tempChar);
                newString += String.valueOf(count);
                count = 1;
            }
            if (message.length() - 1 == i) {
                newString += String.valueOf(tempChar);
                newString += String.valueOf(count);
            }
            tempChar = message.charAt(i);
        }
        System.out.println(newString);
    }

    public static void main(String[] args) {

        String message;
        Scanner scan = new Scanner(System.in);

        System.out.println("문자열을 입력하세요:");
        message = scan.nextLine();
        output(message);
    }
}

2017/03/01 19:50

Bradcha

다들... 장난 아니시네요 ㅋㅋㅋ

def zip(string):
    string += ' '
    n = 1    
    for i in range(1, len(string)):
        if string[i] == string[i-1]:
            n += 1
        else:
            print(string[i-1] + '%d' % n, end='')
            n = 1
    print('')

zip('aaabbcccccca')
zip('####$$&&&&&&!!')
zip('귤귤귤감감배배배배')

2017/03/02 18:46

최해준

static void Main(string[] args)
{
    try
    {
        string strReturn = string.Empty;
        strReturn = GetCompression("aaabbcccccca");

        Console.WriteLine(strReturn);
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        Console.ReadKey();
    }
}

static string GetCompression(string str)
{
    int count       = 0;
    string result   = string.Empty;
    string temp     = string.Empty;
    char[] chArray  = null;

    chArray = str.ToCharArray();
    temp    = chArray[0].ToString();

    for (int i = 0; i < chArray.Length; i++)
    {
        if(!chArray[i].ToString().Equals(temp))
        {
            result += temp + count.ToString();
            temp = chArray[i].ToString();
            count = 0;
        }
        count++;
    }

    result += temp + count.ToString();

    return result;
}

2017/03/05 14:15

bobby

                 String a = "aaabbcccccca";

        char arr[] = a.toCharArray();
        String arrAfter[] =  new String[a.length()];
        int cnt = 0;
        for (char c : arr) {
            Pattern p = Pattern.compile(Character.toString(c));
            Matcher m = p.matcher(a);
             int count  = 0;
             for( int i = 0; m.find(i); i = m.end()){
                 count++;
             }
             String res = Character.toString(c) + count;
             arrAfter[cnt] = res;
             cnt ++;
        }
         TreeSet ts = new  TreeSet();
         for(int i = 0; i < arrAfter.length; i++) {
             ts.add(arrAfter[i]);
         }
         Iterator itor = ts.iterator();
         while(itor.hasNext()) {
               System.out.println(itor.next());
         }

2017/03/08 17:33

박재형

package AlgStudy;

import java.util.Scanner;

public class Alg4 {

    public void compress(String str) {
        StringBuffer sb = new StringBuffer();
        char[] ch = str.toCharArray();
        int aCount = 1;
        for (int i = 0; i < ch.length; i++) {
            if (i == 0) {
                sb.append(ch[i]);
            } else {
                if (ch[i] == ch[i - 1]) {
                    aCount++;
                } else {
                    sb.append(aCount);
                    sb.append(ch[i]);
                    aCount = 1;
                }
                if (i == ch.length - 1) {
                    sb.append(aCount);
                }
            }
        }

        System.out.println(sb.toString());

    }

    public static void main(String[] args) {
        Alg4 main = new Alg4();
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        main.compress(str);
    }
}

2017/03/15 18:07

에라

package training;

import java.util.Scanner;

/**
 * 문자열을 입력받아서, 같은 문자가 연속적으로 반복되는 경우에 그 반복 횟수를 표시하여 문자열을 압축하기.
 * 입력 예시: aaabbcccccca
 * 출력 예시: a3b2c6a1
 *
 */
public class ArchiveString {

    public static void main(String[] args) {
        String strGet = "aaabbccccccca"; // 샘플 문자열1
        //String strGet = "abbccccccca"; // 샘플 문자열2
        //String strGet = "aaabbccccccc"; // 샘플 문자열3
        String strFront = "";
        String strThis = "";
        int iStrCnt = 1;
        StringBuffer sb = new StringBuffer();

        for(int i=0;i<strGet.length();i++){
            strThis = strGet.substring(i, i+1);

            if(strFront.equals(strThis)){
                if(i==strGet.length()-1){ // 마지막 문자열 처리
                    iStrCnt++;
                    sb.append(strFront);
                    sb.append(iStrCnt);    
                } else {
                    iStrCnt++;
                }
            } else {
                if(i==strGet.length()-1){ // 마지막 준자열 처리
                    sb.append(strFront);
                    sb.append(iStrCnt);
                    sb.append(strThis);
                    sb.append(1);
                } else {
                    if(iStrCnt != 1) {
                        sb.append(strFront);
                        sb.append(iStrCnt);                 
                        iStrCnt = 1;
                    } else {
                        if(i == 1 && !strFront.equals(strThis)){ // 첫번째 문자열이 한개일 경우 예외처리
                            sb.append(strFront);
                            sb.append(iStrCnt);                 
                            iStrCnt = 1;
                        }
                    }
                }
            }
            strFront = strThis;
        }

        System.out.println(strGet);
        System.out.println("==>"+sb);

    }

}

2017/04/08 21:52

acedo

#include    <iostream>
#include    <sstream>
using namespace std;
int main( int argc , char** argv )
{
    string  rStr = "aaabbcccccca";
    char    rPrev;
    char    rCurr;
    ostringstream   rResult;
    int     rCount  = 1;
    for( size_t i = 0 ; i < rStr.size() ; ++i )
    {
        rCurr = rStr[ i ];
        if( i == 0 )
        {
            rPrev = rCurr;
            continue;
        }
        if( rCurr ==  rPrev )
        {
            rCount++;
        }
        else
        {
            rResult << rPrev << rCount;
            rCount = 1;
        }
        rPrev = rCurr;
    }
    rResult << rPrev << rCount;
    cout << rResult.str() << endl;
    return  0;
}

2017/04/16 18:09

오승석

private static void compress(String input){
        if(input.length() > 0){
            char c = input.charAt(0);   
            int cnt = 1;

            for(int i=1; i<input.length(); i++){
                if(c == input.charAt(i)){
                    cnt++;
                }else{
                    System.out.print(c);
                    System.out.print(cnt);
                    c = input.charAt(i);
                    cnt = 1;
                }
            }

            System.out.print(c);
            System.out.print(cnt);
        }
    }

2017/04/17 12:39

yh

input="aaabbcccccca귤귤귤감감배배배배"

str=input+'dd'
result=list(str)
result1=[]
k=-1
h=0
for i in result:
    k=k+1
    if k < len(result)-1:
        if i==result[k+1]:
            h=h+1
        else:
            h=0
    result1.append((i,h))
b=-1
for first,last in result1:
    b=b+1
    if b<len(result1)-1:
        if result1[b][-1]>=0 and result1[b+1][-1]==0:
            print("{0}{1}".format(result1[b+1][0],result1[b][-1]+1),end='')

2017/04/18 13:20

조현

import java.util.*;
class Practice01 {
    public static void main(String[] args) {
        /*
            문자열을 입력받아서, 같은 문자가 연속적으로 반복되는 경우에 그 반복 횟수를 표시하여 문자열을 압축하기.
            입력 예시 : aaabbcccccca
            출력 예시 : a3b2c6a1
        */
        Scanner robot = new Scanner(System.in);
        String str = robot.nextLine();
        int cnt = 1;
        for(int i = 0 ; i < str.length()-1; i++){
            if(str.charAt(i) == str.charAt(i+1)){
                cnt++;
            }else{
                System.out.print(str.charAt(i)+""+cnt);
                cnt = 1;
            }
        }
        System.out.println();
    }
}

2017/04/21 15:17

SeonKi Lee

#include <stdio.h>
#include <string.h>
#include <iostream>


using namespace std;

int main()
{
    int i, cnt;


    string s,result;
    getline( cin, s );

    cout<<"s:"<<s<<endl;
    cnt = 0;

    result += s.at(0);

    for(i=1; i< s.length(); i++)
    {   
        if(s.at(i) == s.at(i-1))
        {
            cnt++ ;
        }
        else
        {
            if(cnt)
            {
                result += "1";
                result[result.length()-1] += cnt ;
            }
            cnt = 0;
            result += s.at(i);
        }
    }   
    if(cnt)
    {   
        result += "1";
        result[result.length()-1] += cnt ;
    }   

    cout<<"result:"<<result<<endl;
    return 0;
}

2017/04/29 14:30

Hanbae Seo

def comp(lst):

new_lst=sorted(list(set(lst)))

result=''

for i in new_lst:

    result+=i+str(lst.count(i))

return result

2017/05/06 00:51

정세진

자바로 풀어봤습니다      

        String text = "aaabbccfAAAad";
        StringBuffer sb = new StringBuffer();

        int count = 1;
        for(int i=0; i<text.length(); i++) {
            if(i != text.length()-1) {
                char strandardChar = text.charAt(i);
                char compareChar = text.charAt(i+1);

                if(strandardChar == compareChar) {
                    count++;
                }else {
                    sb.append("" + strandardChar + count);
                    count = 1;
                }

            // 마지막 문자 처리    
            }else {
                char strandardChar = text.charAt(i);
                sb.append("" + strandardChar + count);
            }
        }

        System.out.println(sb.toString());

2017/05/10 11:35

양민우

inputString = "abbcccdddd"
inputStringList = list(inputString)
outputString = ""
number = 1

for i in range(len(inputString)):
    if i == 0:
        outputString += inputString[i]
    elif inputString[i] == inputString[i-1]:
        number += 1
        if i == len(inputString)-1:
            outputString += str(number)
    else:
        outputString += str(number)
        outputString += inputString[i]
        number = 1

print(outputString)

2017/05/10 16:18

Taewon Song

Java로 작성했습니다.

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int count = 1, i = 0;

        while (true) {
            if (i == s.length() - 2) {
                System.out.print(s.charAt(i) + "" + (count + 1));
                break;
            } else if (s.charAt(i) == s.charAt(i + 1)) {
                count++;
                i++;
            } else if (s.charAt(i) != s.charAt(i + 1)) {
                System.out.print(s.charAt(i) + "" + count);
                i++;
                count = 1;
            }
        }
    }
}

2017/05/12 17:22

Dangerous Escape

def compress(N):

length = len(N)
i = 0
List1 = []
List2 = []
while(i < length-1):

    t1 = N[i]
    t2 = N[i+1]
    if t1 == t2:
        List1.append(t1)
        if i == length-2:
            List1.append(t2)
            counter = List1.count(t1)
            List2.append(t1)
            List2.append(str(counter))
    elif t1 != t2 :
        List1.append(t1)
        counter = List1.count(t1)
        List2.append(t1)
        List2.append(str(counter))
        List1 = []
        if i == length-2 :
            List1.append(t2)
            counter = List1.count(t2)
            List2.append(t2)
            List2.append(str(counter))

    i += 1  
return "".join(List2)

2017/05/14 16:38

김순효

c로 풀이


#include <stdio.h>
int main(void)
{
    int i,num=0;
    char s[20];

    printf("입력 : ");
    scanf("%s",s);

    for(i=0;i<20;i++)
    {
        if (s[i]==s[i-1]) num++;
        else
        {
            if(num!=0) printf("%d",num);
            printf("%c",s[i]);
            num=1;
        }
        if(s[i]=='\0') break;
    }
    return 0;
}

2017/05/31 11:13

박동준


text = input("text : ")

x = [text[i] for i in range(0,len(text))]

count = 1
a = x[0]+str(count)
b = []

for i in range(1,len(x)):
    if x[i-1] == x[i]:
        count = count + 1        
        a = x[i-1]+str(count)
    else:
        b.append(a)
        count = 1
        a = x[i]+str(count)


b.append(a)

print ("compress :",''.join(b))


2017/06/13 13:30

Bo Hyun Seo

let count = 1;
let line = '';

let loopFunc = (str) => {
    for(let i = 0; i < str.length; i++){
        if(str.charAt(i) == str.charAt(i+1)){
            count++;
        }else{
            line += (str.charAt(i)+count);
            count = 1;
        }
    }
    return line;
}

console.log(loopFunc('aaabbcccccca'));

2017/06/14 22:25

redshark

import java.util.Scanner;

public class A {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String sentence = scan.next();

        long start = System.nanoTime();
        /* 현재 글자 */
        char now = sentence.charAt(0);
        /* 이전 글자 */
        char pre = now;
        /* 결과 스트링버퍼 */
        StringBuffer sb = new StringBuffer();
        sb.append(now);
        /* 글자 수 */
        int chaCount = 1;

        for(int i=1;i<sentence.length();i++){
            now = sentence.charAt(i);
            /* 같은 글자일 경우 카운트만 + / 다른 글자일 경우 글자 수를 붙이고 현재 글자를 붙임 */
            /* 카운트를 1로 하고 이전 글자를 현재 글자로 변경 */
            if(now != pre){
                sb.append(chaCount);
                sb.append(now);
                chaCount = 1;
                pre = now;
            }else{
                chaCount += 1;
            }
            if(i == sentence.length()-1) sb.append(chaCount);
        }
        long end = System.nanoTime();

        System.out.println(sb);
        System.out.println(end-start);
    }
}

2017/06/28 15:13

최현석

i=0
num=1
nums=[]
value_list=[]

value  = input("입력: ")

for member in range(len(value)-1):
    if value[i] != value[i+1]:
        value_list.append(value[i])
    i = i+ 1

value_list.append(value[len(value)-1])

i=0
for member in range(len(value)-1):
    if value[i] == value[i+1]:
        num = num+1
        i = i+1

    else:
       nums.append(num)
       num = 1
       i = i +1

nums.append(1)


i=0
for member in range(len(nums)):
    print(value_list[i]+str(nums[i]),end='')
    i=i+1

2017/07/01 11:04

안성준

s = 'aaaaaaaaaaa'
#s = 'aaaabbbbb'
#s = 'aaaabbbbc'

ans = ''
count = 1 


for i in range(len(s)-1):

    if s.count(s[i]) == len(s):
        ans = s[0] + str(len(s))
        break


    if s[i] == s[i+1]:
        count+=1

        if i == len(s)-2:
            ans = ans + s[i] +str(count)

    else:
        ans = ans + s[i]+str(count)
        count = 1

        if i == len(s)-2:
            ans = ans + s[i+1] + str(count)


print ans

2017/07/04 17:21

강동인

JAVA입니다.


public class EX010 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //문자열입력
        StringBuffer orgStr = getInputString();
        //작업 및 출력
        System.out.println("압축된 문자열: " + compressString(orgStr));
    }

    static private StringBuffer compressString(StringBuffer orgStr) {
        for(int i=0; i < orgStr.length(); i++) {
            //현재 문자가 숫자라면 건너띈다.
            if(isString2Int(Character.toString(orgStr.charAt(i))))
                continue;
            //같은문자 count변수, 문자검사 시 이동하는 index변수
            int charCount = 0;
            int curIdx = i;
            //현재 위치(i)부터 다음 문자를 계속 탐색하며 같은 문자라면 charCount++, 다르다면
            while(orgStr.charAt(i) == orgStr.charAt(curIdx)) {
                charCount++;
                curIdx++;
                //문자열의 마지막인지 검사
                if(curIdx > orgStr.length()-1 )
                    break;
            }

            orgStr.replace(i, curIdx, Character.toString(orgStr.charAt(i)) + String.valueOf(charCount));
        }

        return orgStr;
    }

    //int형 수인지 검사
    static private boolean isString2Int(String str) {
        try {
            Integer.parseInt(str);
            System.out.println("true");
            return true;
        }catch(NumberFormatException e) {
            System.out.println("false");
            return false;
        }
    }

    //입력
    static private StringBuffer getInputString() {
        Scanner scan = new Scanner(System.in);
        System.out.print("압축할 문자열: ");
        return new StringBuffer(scan.nextLine());       
    }
}

결과는 문제에 나와있는 것과 같이 나옵니다.

2017/07/04 19:08

pg

정규표현식을 이용하여 Python으로 풀었습니다.

import re
def zip_by_char(s):
    return ''.join('%s%d' % (cs.group(0)[0], len(cs.group(0))) for cs in re.finditer(r'(\w)\1*', s))

2017/07/07 13:15

SOUP

package java_tutorial;

import java.util.Scanner;

public class RepeatComp {

    public static void main(String[] args) {



        Scanner sc = new Scanner(System.in);

        System.out.print("입력 예시 : ");
        String myWords = sc.next();

        char wordSave = myWords.charAt(0);
        int count = 0;

        for(int i = 0; i < myWords.length(); i++)
        {       

                if(wordSave == myWords.charAt(i))
                {                       
                        count++;
                }
                else
                {                   
                        System.out.print(wordSave);
                        System.out.print(count);
                        count = 1;
                }

                wordSave = myWords.charAt(i);

                if(i==myWords.length()-1)
                {
                        System.out.print(wordSave);
                        System.out.print(count);
                }
        }       

    }

}

2017/07/18 17:54

최원석

C#

using static System.Console;

class StringCompaction
{
    static void Main(string[] args)
    {
        string str = "aaabbcccccca";

        char ch = str[0];
        int cnt = 1;    
        for (int i = 1; i < str.Length; i++)
        {
            if (str[i] != ch)
            {
                Write("{0}{1}", ch, cnt);
                ch = str[i];
                cnt = 1;
            }
            else
            {
                cnt++;
            }
        }
        Write("{0}{1}", ch, cnt);
    }
}

2017/07/19 20:05

Noname

import re
a="aaabbbcccdde"
string=""
filted = re.findall("(\w)(\\1*)", a)
for i in range(0,len(filted)) :
               result=filted[i][1]
               c=len(result)
               string+=filted[i][0]+str(c+1)
print(string)

2017/07/25 19:20

박준

def run_length(string) :
    result = ''
    count = 1

    for i in range(1, len(string)) :

        if string[i] == string[i-1] :
            count += 1

            if i == len(string) - 1 :
                result = result + string[i-1] + str(count)

        else :
            if count == 1 :
                result = result + string[i-1]
            else :
                result = result + string[i-1] + str(count)

            count = 1

            if i == len(string) - 1 :
                result = result + string[i]

    return result

string1 = input("any serial string : ")
print(run_length(string1))

2017/07/29 20:51

다크엔젤

python 3.6.2입니다

a = input("input: ")
a_list = list(a)
a_set_list = list(set(a))
for i in a_set_list:
    res += i + str(a_list.count(i))

print(res)

set을이용해 중복을없앤후 for을 이용해 중복없는 리스트 a_set_list의 문자를 중복이잇는 a_list에서 카운트하는방식으로 햇습니다

2017/08/05 08:37

시간의마법

list=list(str).sorted count=list.count(list[0]) new.append(list[0]) new.append(count) for i in range(count): list.remove(list[0])

2017/08/11 05:15

김초영

def getCnt(str1):
    cnt = 0
    result = ''
    for idx1, char1 in enumerate(str1):
        cnt += 1
        if idx1 == (len(str1)-1) or char1 != str1[idx1+1]:
            result += char1 + str(cnt)
            cnt = 0
    print(result)

getCnt('aaabbcccccca')

2017/08/24 11:33

piko


public class Example73 {

    public static void main(String[] args) {
        String s = "aaabbccccccabb";

        Example73 ex = new Example73();
        System.out.println(ex.compact(s));
    }

    private String compact(String s) {

        StringBuilder sb = new StringBuilder();
        char c = ' ';
        int count = 1;

        for (int i = 0; i < s.length(); i++) {
            c = s.charAt(i);

            if ((i + 1) < s.length() && s.charAt(i) == s.charAt(i + 1)) {
                ++count;
            } else {
                sb.append(c);

                if (count != 1)
                    sb.append(count);

                count = 1;
            }
        }

        return sb.toString();
    }
}

2017/09/05 11:51

흑돼지

public class Code73 {

    public static void main(String[] args) {

        String str = "aaabbbbbcca";

        System.out.println(compressString(str).toString());

    }

    public static StringBuffer compressString(String str) {

        String sub = str + (char)(str.charAt(str.length()-1)-1);
        StringBuffer sb = new StringBuffer();

        for (int i=1, offSet=0; i<sub.length(); i++) {

            if (sub.charAt(i) != sub.charAt(i-1)) {
                sb.append(sub.charAt(i-1) + "" + (i-offSet));
                offSet = i;
            }

        }       
        return sb;
    }

}

경계값 처리는 언제나 힘들군요..

2017/09/08 09:15

박성호

# python 3.6
string = "aaabbcccccca"
cnv = ("".join([string[i] if string[i] == string[i + 1]
                else string[i] + "," for i in range(len(string) - 1)]) + string[-1]).split(",")
cmpd = "".join([s[0] + str(len(s)) for s in cnv])
print(cmpd)

2017/09/09 13:08

mohenjo

파이썬이에용

X = input()//if you inputs "abcbbca"

X=sorted(list(X))//X = ['a','a','b','b','b','c','c']

z = list(set(X))// z = ['b','c','a']

for i in range(len(z)): print(z[i],X.count(z[i]))

// 리스트 요소들의 개수를 세주는 count메소드에용 //list.count(obj) : The method count() returns count of how many times obj occurs in list.

2017/09/15 23:48

명혜미

python 2.7 로 작성

def run_length_encode(s):
    last = s[0]
    res = [last]
    count = 1
    for x in s[1:]:
        if x == last:
            count += 1
        else:
            res.append(str(count))
            last = x
            res.append(last)
            count = 1
    res.append(str(count))

    return ''.join(res)

ipython 에서의 출력입니다.

In [128]: run_length_encode('aaabbcccccca')
Out[128]: 'a3b2c6a1'

2017/10/07 23:59

jkgim

#include <stdio.h>
int main(void){
    int con=1;
    char arr[10]={0};

    scanf("%s",arr);

    for(int i=0;i<10;i++){
        if(arr[i]==arr[i+1])
        con++;
        else {
        printf("%c%d",*(arr+i),con);
        con=1;} 
}
}

C로 풀었습니다.

2017/10/10 13:47

손세찬

package codingdojang;

import java.util.Scanner;

public class ex73 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);

    String a = sc.nextLine();
    int count = 1;

    String result = "";

    for(int i=0; i<a.length(); i++) {
        char temp = a.charAt(i);
        if(i+1 == a.length()) {
            result = result+temp+count;
            break;
        }
        if(temp == a.charAt(i+1)) {
            count++;
        }else {
            result = result+temp+count;
            count = 1;
        }
    }

    System.out.println(result);
}

}

2017/10/17 15:43

이병호

    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            StringBuilder sb = new StringBuilder();
            int count = 0;
            for (int i = 0; i < str.Length ; i++)
            {
                char front = str[i];
                char back = ' ';
                if (i != str.Length - 1)
                {
                   back = str[i + 1];
                }                

                if(front == back)
                {
                    count++;
                }
                else
                {
                    count++;
                    sb.Append(str[i].ToString() + count.ToString());
                    count = 0;
                }
            }
            Console.WriteLine(sb.ToString());
        }

2017/11/17 21:44

김종철

const comp = str => {
  let count = 0;
  let result = str.split('').reduce((s, v) => {
    if (s.charAt(s.length - 1) === v) {
      count++;
    } else {
      s += count += v;
      count = 1;
    }
    return s;
  }, str.charAt(0));
  result += count;
  return result;
};
console.log(comp('aaabbcccccca'));

2017/11/24 12:09

huna

private static void compress(String input){
        if(input.length() > 0){
            char c = input.charAt(0);   
            int cnt = 1;

            for(int i=1; i<input.length(); i++){
                if(c == input.charAt(i)){
                    cnt++;
                }else{
                    System.out.print(c);
                    System.out.print(cnt);
                    c = input.charAt(i);
                    cnt = 1;
                }
            }

            System.out.print(c);
            System.out.print(cnt);
        }
    }

2017/12/04 16:27

떼디

txt = "aabcccaaaaas"

strr = txt[0]

cnt = 0

for i in range(len(txt)) :

    if strr[-1] == txt[i] : #strr[-1]:: 마지막 값을 가져온다 !

        cnt+= 1
    else :
        strr += "{0}".format(cnt)
        strr += txt[i]
        cnt =1
strr+=str(cnt)
print(strr)

2017/12/16 19:08

얏홍

def counter(s):
    tmp=list(s)
    result=''
    def inner(t, r):
        a=t.pop(0)
        if not t: return(r+a+'1')
        n=0
        while True:
            if t and t[0]==a:
                t.pop(0)
                n+=1
            else: break
        r=r+a+str(n+1)
        if not t: return(r)
        else: return(inner(t, r))
    return(inner(tmp, result))

A=input()

print(counter(A))

2017/12/17 03:30

빗나감

package programming;

import java.util.Scanner;

public class repeat {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input;
        int count = 1; // 카운트를 1로 초기화

        System.out.println("문자열을 입력하시오:");
        input = sc.next();

        for (int i = 0; i < input.length(); i++) {

            if (i + 1 == input.length()) { // 배열의 범위를 넘어서면 마지막 문자를 출력하고 반복문 탈출
                System.out.printf("%c%d", input.charAt(i), count);
                break;
            } else if (input.charAt(i) == input.charAt(i + 1)) // 앞문자와 뒷문자가 같다면 카운트 증가
                count++;
            else {
                System.out.printf("%c%d", input.charAt(i), count); // 앞문자와 뒷문자가 다르다면 현재까지의 카운트와 문자 출력
                count = 1;
            }

        }

    }

}

2017/12/20 15:18

쫑티

input = 'aaabbccccaccaaa'
output = ''
input = ' '.join(input).split() + [' ']
while input != [' ']:
    i = 1
    while input[0] == input[1]:
        del input[0]
        i = i + 1
    output = output + input[0] + str(i)
    del input[0]
print(output)

2017/12/30 19:41

김호현

자바 입니다... 허허...

String str = "aaabbcccccca";


    public static void main(String[] args)
    {
        main m = new main();
        System.out.println(m.cntChar());
    }


    public String cntChar()
    {
        int cnt = 1;
        char tmp = ' ', character;
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < str.length(); i++)
        {
            character = str.charAt(i);
            if(tmp == ' ')
            {
                tmp = character;
            }
            else
            {
                if(tmp == character)
                    cnt++;
                else
                {
                    sb.append(String.valueOf(tmp)+cnt);
                    cnt = 1;
                    if(i == str.length()-1)
                    {
                        sb.append(String.valueOf(character)+cnt);
                    }
                }

                tmp = character;
            }
        }
        return sb.toString();
    }

2018/01/08 17:12

강승규

파이썬 3.6

def strcompress(s):
    m,new_s = 1,''
    for i,value in enumerate(s):
        if i == 0: new_s += value
        else:
            if s[i] == s[i-1]: m += 1
            elif s[i] != s[i-1]:
                new_s += str(m) + value
                m = 1
                if i == len(s)-1: new_s += str(m)               
    print(new_s)

if __name__ == "__main__":
    s = 'aaabbcccccca'
    strcompress(s)
  • 결과값
a3b2c6a1

2018/01/13 13:25

justbegin

r로 풀었습니다.

zipfun<-function(x){
v1<-unlist(strsplit(x,split = character(0)))
v2<-unique(v1)
r<-rep(NA, length(v2))
k<-1
i<-2
j<-1
r[1]<-v1[1]
while(i<=length(v1)){
  if(v1[i]==v1[i-1]){
    k<-k+1
  }else{
    r[j]<-paste0(r[j],k)
    j<-j+1
    r[j]<-v1[i]
    k<-1
  }
  i<-i+1
}
r[j]<-paste0(r[j],k)
result<-NULL
for(n in 1:length(r)){
  result<-paste0(result, r[n])
}
print(result)
}

zipfun("aaabbcccccca")

2018/01/21 20:58

Seunghyuck Kim

st<-function(...){
  temp<-c(...)
  count<-1
  num<-NULL
  result<-NULL
  for(i in 2:NROW(temp)){
    if(temp[i-1]==temp[i]){
      count<-count+1
      num<-count
    }else{
      result<-c(result,temp[i-1],num)
      count<-1
    }
  }
  result<-c(result,temp[i],num)
  print(result)
}
st('a','a','a','b','b','c','c','a','a','a')

2018/01/24 09:55

Dong-il kim

# 파이썬

input_s1 = "aaabbcccccca"


def s_comp(s):
    r = str(s[0])
    i = 1
    for m in range(len(s)-1):
        if s[m] == s[m+1]:
            i += 1
        else:
            if i >= 2:
                r += str(i)
            r += s[m+1]
            i = 1
    return r


print(s_comp(input_s1))

2018/01/30 12:15

olclocr

def strzip(a):
    b = list()
    for i in range(0, len(a)-1):
        if a[i] != a[i+1]:
            b.append(i)
    if b == []:
        return a[0]+str(len(a))
    else:
        c = a[b[0]]+str(b[0]+1)
        for j in range(1, len(b)):
            c += a[b[j]]+str(b[j]-b[j-1])
        c += a[len(a)-1]+str(len(a)-1-b[len(b)-1])
        return c


print(strzip(input()))

2018/02/12 19:02

김동하

#include <stdio.h>
#include <string.h>

int main(){
    char str[50];
    int cnt=1;
    int i=0;
    int len;
    scanf("%s",str);
    len=strlen(str);
    for(i=0; i<strlen(str); i++){
        if(str[i]==str[i+1]) cnt++;
        else{
            printf("%c%d",str[i],cnt);
            cnt=1;
        }
    }
}

2018/02/16 13:43

gudrhrehd123

for_change=input("바꾸려는 문자열을 입력하세요:")
counter=1
temp_str=for_change[0]
ans=''
for index in range(1,len(for_change)):
    if for_change[index]==temp_str:
        counter+=1
        if index==len(for_change)-1:
            ans+=temp_str+str(counter)
    elif for_change[index]!=temp_str:
        ans+=temp_str+str(counter)
        counter=1
        temp_str=for_change[index]
        if index==len(for_change)-1:
            ans+=temp_str+str(counter)

print(ans)

2018/02/22 02:03

D B

def strzip(string):
    repeat = [0]
    result = ''
    for args in string:
        if args == repeat[0]:
            repeat.append(args)
        else:
            if repeat[0] != 0:
                result = result + repeat[0] + str(len(repeat))
            repeat[:] = args
    result = result + repeat[0] + str(len(repeat))
    return result

Python 3

2018/03/23 00:39

myyh2357

string = 'appleeeesswz'

string_list = []
count = 1

for i in range(len(string)-1) :
    if string[i] == string[i+1] :
        count += 1
        if len(string)-2 == i :
            string_list.append(string[i])
            string_list.append(str(count))
    else :
        string_list.append(string[i])
        string_list.append(str(count))
        count = 1
        if len(string)-2 == i :
            string_list.append(string[i+1])
            string_list.append(str(count))
print(''.join(string_list))


2018/03/26 17:37

박강민

def zips():
    code=[]
    n=str(input('입력하세요: '))
    num=1
    for i in range(1,len(n)):
        if n[i]==n[(i-1)]:
            num+=1
        else :
            code.append(n[i-1]+str(num))
            num=1
    code.append(n[i]+str(num))
    print(''.join(code))

2018/04/06 10:33

thuruk

Swift입니다.

import Foundation

func compress(_ input: String) -> String {
    var count = 0
    var result = ""

    for item in input {
        if item != result.last {
            result.append(count > 0 ? String(count) : "")
            count = 1
            result.append(String(item))
        } else {
            count += 1
        }
    }
    result.append(String(count))    
    return result
}

print( compress("aaabbcccccca"))

2018/04/10 13:24

졸린하마

import java.util.Scanner;

public class list{
 public static void main(String[] args){
  Scanner sc = new Scanner(System.in);
  System.out.print("입력해 : ");

  String input = sc.nextLine();

  int count=0;

  for(int i=0 ;i<input.length()-1 ;i++){
   if(input.charAt(i) == input.charAt(i+1)){
    count++;
    if(i==input.length()-2)
     System.out.print(input.charAt(i) + "" + (count+1));
   }
   else{
     System.out.print(input.charAt(i) + "" + (count+1));
     count = 0;
    if(i==input.length()-2)
     System.out.print(input.charAt(i+1) + "" + (count+1));
   }

  }

 }
}

2018/04/28 18:12

배혜민

public class practice {

public static void main(String[] args) {

    String str = "aaabbcccccac";
    StringBuffer sb = new StringBuffer();
    int count = 1; //비교 대상과 자기자신까지 포함해야해서 count는 1
    int j=0;
    for (int i=0; i<str.length(); i++) {
        char tmp = str.charAt(i); // 처음에 나온 문자
        for (j=i+1; j<str.length(); j++) {
            char a = str.charAt(j); // tmp와 비교할 문자
            if (tmp == a) 
                count++; // 같을 때 문자 카운트
             else  
                break; // 다르면 바로 빠져나옴
        }
        sb.append(tmp).append(count); 
        count = 1;
        i = j-1; // i를 j의 위치로 바꿔준다
    }
    System.out.println(sb);
}

}

자바입니다. 다시 풀었어요.

2018/05/03 09:14

정몽준

user_input = input()

def contract(string):
    idx = 0
    count = 1
    result = ''

    while (idx+1) != (len(string)):

        if string[idx] == string[idx+1]:
            idx += 1
            count += 1

            if idx+1 == len(string)-1 and string[idx+1] == string[idx]:
                count += 1
                result = result + string[idx] + str(count)
                break

        else:
            result = result + string[idx] + str(count)
            idx += 1
            count = 1


    if string[-1] != string[-2]:
        result = result + string[-1] + '1'

    return result


print(contract(user_input)) # aabbbccc = > a2b3c3

2018/05/07 02:07

최우성

#include <stdio.h>

int main() {
    char str[] = "aaabbccccccaaaaaaacccc", temp[1000] = { 0, };
    int length = sizeof(str) * sizeof(char), i = 0, index = 0;
    while (++i < length) {
        temp[index] = str[i-1];
        temp[index + 1]++;
        if (str[i-1] != str[i])
            index += 2;
    }
    temp[index + 2] = '\0';
    index = 0;
    while (temp[index] != '\0')
        printf(index % 2 == 0 ? "%c" : "%d", temp[index++]);
}

2018/05/31 19:18

남해

a = 'aaabbcccddddee'
result = "".join([sorted(set(a))[i] + [str(a.count(x)) for x in sorted(set(a))][i] for i in range(len(sorted(set(a))))])

2018/06/04 17:55

배동준

aaabbccccccca a, count=1, next=a; a, count=2, next=a; a, count=3, next=b; a3 b, count=1, next=b; b, count=2, next=c; a3b2

  private static String stringCount(String input){
    StringBuffer newStr = new StringBuffer();
    String temp = input + " ";
    char[] chArr = temp.toCharArray();
    int count = 0;
    for(int i = 0; i < input.length(); i++){
      if(chArr[i]==chArr[i+1]){
        count++;
      }else{
        newStr.append(String.valueOf(chArr[i]));
        newStr.append(++count);
        count = 0;
      }
    }
    return newStr.toString();
  }
  public static void main(String[] args){
    System.out.println(stringCount("####$$&&&&&&!!"));
  }

2018/06/05 21:35

Namgee Lee

def compression(x):
    j=[]
    x=list(x)
    while len (x) > 1:
        if x[1] in x[0]:
            x[1] = x[0]+x[1]
            x = x[1:]
        else:
            j.append(x[0])
            x=x[1:]
    j.append(x[-1])  
    k = [i[0]+str(len(i)) for i in j]
    k = "".join(k)           
    return k

2018/06/06 08:31

Kwak, Chuljung

Python

a = "aaabbcccccc"
ans = a[0]
cnt = 0
for c in a:
    if c == ans[-1]:
       cnt += 1
    else:
        ans += str(cnt) + c
        cnt = 1
ans += str(cnt)
print(ans)

2018/06/07 16:59

Taesoo Kim

s = 'aabcccaaaaas'

s += "--"
count,comp = 1,""

for i in range(1,len(s)):
    if s[i] ==  s[(i-1)]:
        count +=1
    else:
        comp += s[i-1]+str(count)
        count = 1

2018/06/19 10:17

프로젝트1교통약자석

#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;

string StringFromNumber(const int value) 
{
    stringstream ss;
    ss << value;
    return ss.str();
}

int main()
{
    vector<int> v, str;
    string name = "aaabbccccca";
    string name_compress = "";
    int count = 1;
    int c_count = 0;
    str.push_back(c_count);

    for (int i = 0; i < name.size(); i++)
    {
        c_count++;
        if (name.substr(i + 1, 1) == name.substr(i, 1))
        {
            count++;
        }
        else
        {
            v.push_back(count);
            count = 1;
            str.push_back(c_count);
        }
    }
    for (int i = 0; i < v.size(); i++)
    {
        name_compress.append(name.substr(str[i], 1));
        name_compress.append(StringFromNumber(v[i]));
    }
    cout << name_compress;
}

2018/06/19 19:52

Jun ki Kim

def compress(str1, temp='', temp_len=0):
    for c in str1:
        if temp and temp[-1] == c:
            temp_len += 1
        else:
            temp += str(temp_len) + c
            temp_len = 1
    temp += str(temp_len)    
    return temp[1:]

print(compress('aaabbcccccca'))

2018/07/07 20:05

재즐보프

x = input()
r,old,c = '','old',1
for i in x:
    if i == old: c += 1
    else:
        r += str(c)+i
        old,c = i,1
r = r[1:]+str(c)
print(r)

2018/07/18 20:26

Creator

string = input()
result = ""
count = 0; memory = ''

for i in string:
    if(count==0):
        result += i
        count += 1; memory=i
    else:
        if(i == memory): count+=1
        else:
            result += str(count)
            result += i
            count=1; memory=i
result+=str(count)

print(result)

2018/07/30 00:14

박용주

package practice;

public class test {
    public static void main(String[] args) {
        String str = "aaabbcccccca";
        String result = "";
        int count = 1;
        for (int i = 0; i < str.length(); i++)
            if (i + 1 < str.length() && str.charAt(i) == str.charAt(i + 1)) {
                count++;
            } else {
                result += str.charAt(i) + (count + "");
                count = 1;
            }
        System.out.println(result);
    }
}

2018/08/18 17:57

김성우

python 2.7

def string(x):
    ans1 = [list(x)[0]]
    ans2 = [1]
    for a in list(x)[1:]:
        if a==ans1[-1]:
            ans2[-1] = ans2[-1]+1
        else:
            ans1.append(a)
            ans2.append(1)
    b = []
    for i in range(len(ans1)):
        b.append(ans1[i])
        b.append(str(ans2[i]))
    return("".join(b))

2018/09/06 16:52

tarte24

python입니다. 파이썬은 시작한지 얼마 안되서 코드가 많이 기네요..

a=-1; b=0; c=1; t=list(input(":"))
d=t[0]
n=len(t)
print(n)
while (a<n-2):
    a+=1
    b+=1
    if str((t[a])) == str((t[b])):
        c+=1
    else:
        d+=str(c)+t[b]
        c=1
d+=str(c)
print (d)

2018/09/08 20:15

Luzz

//  =============================================
        String st = "aaabbcccccca";

        int count = 1;
        for (int i = 0; i < st.length(); i++) {
            if (i + 1 < st.length() && st.charAt(i) == st.charAt(i + 1)) {
                count++;
            } else {
                System.out.print(st.charAt(i) + "" + count);
                count = 1;
            }
        }

2018/09/14 16:44

채규빈

s = "aaabbcccccaeexxyyz"
temp_s = ""
print_s = ""
cnt  = 0
for index, i in enumerate(s):
    if index == 0:
        temp_s = i
        cnt = 1
    else:
        if temp_s == i:
            cnt = cnt + 1
        else:
            print_s = print_s + temp_s+ str(cnt)
            temp_s = i
            cnt = 1

    if len(s) == index + 1:
        print_s = print_s + temp_s+ str(cnt)            

print(print_s)

2018/10/23 10:48

Dae Su Jeong

public class Answer{

    public static void main(String[] args) {
        System.out.println("문자열을 입력하시오 : ");

         Scanner sc = new Scanner(System.in);
            String data = sc.nextLine() + " ";
            String a = "";      
            int count = 1;
            for (int i = 0; i<data.length()-1; i++)
                if (data.charAt(i) == data.charAt(i + 1))
                    count++;
                else {
                    a += data.charAt(i) + (count + "");
                    count = 1;
                }
            System.out.println(a);
    }
}

2018/11/05 14:30

황세호

def count_repeat() :
    input_str = input("입력")
    result = []
    cnt = 1
    for i in range (0, len(input_str)-1) :
        # 앞뒤 문자가 같을 경우
        if input_str[i]==input_str[i+1] :
            cnt+=1
            # 마지막 문자
            if i==len(input_str)-2 : 
                result.append(str(input_str[i]))
                result.append(str(cnt))
            continue
        # 앞뒤 문자가 다를 경우    
        else :
            result.append(str(input_str[i]))
            result.append(str(cnt))
            cnt=1
            # 마지막 문자
            if i == len(input_str)-2 :
                result.append(str(input_str[i+1]))
                result.append(str(cnt))
                continue

    str_result = "".join(result)
    return str_result

2018/11/05 22:55

쨔이

Java 8

public class tut04 {
  public static void main(String[] args) {
    System.out.println("hello world");

    String input = "aaabbbccca";  // 입력값
    String reuslt = "";                   // 결과값
    System.out.println("input  : " + input);

    // input 에 공백을 앞뒤에 추가.
    input = " " + input + " ";

    // input 을 CharArray 로 변환
    char[] chars = input.toCharArray();

    // 공백을 제외한 각 글자수 만큼 반복.
    int cnt = 1;
    for (int i = 1; i < chars.length-1; i++) {
      if ( chars[i] == chars[i+1]  ) {
        cnt++;
      } else {
        reuslt += chars[i] + "" + cnt;
        cnt = 1;
      }
    }
    System.out.println("result : " + reuslt);
  }
}

2018/11/30 22:06

Oracle Query

WITH t1 AS (SELECT t1.words, SUM(t1.cnt) over(ORDER BY 1 rows BETWEEN unbounded preceding AND CURRENT ROW) AS gubun FROM (SELECT substr('aaabbcccccca', LEVEL, 1) AS words, decode(LEVEL, 1, 1, decode(substr('aaabbcccccca', LEVEL, 1), substr('aaabbcccccca', LEVEL - 1, 1), NULL, LEVEL)) AS cnt FROM dual CONNECT BY LEVEL <= length('aaabbcccccca')) t1)

SELECT listagg(t2.r) within GROUP(ORDER BY t2.gubun) hobbys FROM (SELECT t1.words, t1.gubun, COUNT(1), t1.words || COUNT(1) AS r FROM t1 GROUP BY t1.words, t1.gubun ORDER BY t1.gubun) t2 ;

2018/12/01 11:20

#문자열 압축하기
test=str(input('입력: '))
result=test[0]
count=0

for i in test:
    if i == result[-1]:
        count +=1
    else:
        result += str(count) + i
        count = 1
result+=str(count)

print(result)

2018/12/01 17:34

S.H

#HiCode
S = 'aaabbbccadgggg'
a = 'abcdefghijklmnopqrstuvwxyz'
''.join([i+str(S.count(i)) for i in a if S.count(i)])

2018/12/26 10:07

김혜인

def str_pr(input_str):
    li = list(input_str)
    result = li[0]
    count = 0

    for i in li:
        # 마지막 문자와 비교
        if i is result[-1]:
            count += 1

        # 다른 문자 나올 경우 result에 문자 추가한 뒤 카운터 초기화
        else:
            result += str(count) + i
            count = 1

    # 마지막 문자 카운팅 표기
    result += str(count)

    return print(result)

def main():
    user_input = input("Input string : ")
    str_pr(user_input)

if __name__ == '__main__':
    main()

2019/01/04 11:11

김범식

word = input("문자열을 입력하세요: ")
temp = word[0] #비교할 문자 저장
compress = word[0] #압축된 문자
count = 0

for i in word:
    if temp == i:
        count += 1
    else:
        compress += str(count) + i
        count = 1
    temp = i

print(compress + str(count))

2019/01/10 16:01

달품

def comp(s):
    xl,c = s[0],0
    for x in list(s)+['0']:

        if x == xl:
            c += 1
        else:
            print('%s%d' %(xl,c), end = '')
            c = 1
            xl = x

2019/01/12 10:22

김영성

plainText = 'aaabbccccccaac'

def comp(targetText):
    targetText=targetText+' '
    count = 1
    destText = ''
    for idx in (range(0, len(targetText)-1)):
        if targetText[idx] == targetText[idx+1]:
            count += 1
        else:
            destText += targetText[idx]
            destText += str(count)
            count = 1
    return destText
print(comp(plainText))

2019/01/17 13:24

선선모


#include<vector>
#include<iostream>
#include<string>


using namespace std;

int main(void)
{
    int cnt = 0;
    string s;
    vector<char>cv;

    getline(cin, s);
    for (int i = 0; i < s.length(); i++)
    {
        cv.push_back(s[i]);
    }
    for (int i = 0; i < cv.size(); i++)
    {
        if (i > 0)
        {
            if (cv[i - 1] == cv[i])
            {
                cnt++;
                if (i == cv.size() - 1)
                {
                    cout << cv[i] << cnt+1;
                }

            }
            else
            {

                cout << cv[i - 1] << cnt+1;
                cnt = 0;
                if (i == cv.size() - 1)
                {
                    cout << cv[i] << "1";
                }
            }
        }
        else
        {

        }
    }


}//문자열끝의 조건 분류하는것이 어려웠음

2019/01/21 04:30

김상범

자바로 풀어봤습니다!

import java.util.*;

class CompressString {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        input = input + "_"; //입력받은 String의 끝을 알린다

        String output = "";
        int counter = 1;

        for(int i=1; i<input.length();i++) {
            if(input.charAt(i) == input.charAt(i-1)) {
                counter++;
            }
            else if(input.charAt(i) == '_'){
                output = output + input.charAt(i - 1) + counter;
            }
            else {
                output = output + input.charAt(i-1) + counter;
                counter = 1;
            }
        }   
        System.out.println(output); //결과 출력
    }
}

2019/01/23 10:47

고요정

tuple=input("입력하시오")
mtuple=",".join(tuple)
list=mtuple.split(",")
print(list)
count=0
for i in range(len(list)):
      if i<len(list)-1:
            if list[i]==list[i+1]:
                  count+=1
            elif list[i]!=list[i+1]:
                  print(list[i]+str((count+1)),end="")
                  count=0
      else:
            print(list[i]+str(count+1))

2019/01/27 20:46

이상승

s = input()
compare = s[0]
count = 0
result = []

for i in s:
    if i == compare:
        count += 1
    else:
        if count > 1:
            result.append(compare + '{}'.format(count))
            count = 1
    compare = i

    if i == s[len(s)-1]:
        if count > 1:
            result.append(compare + '{}'.format(count))
for i in result:
    print(i, end = '')

2019/02/01 11:09

D.H.

[Python] 입력받은 문자열을 같은것끼리 순차적으로 묶은 후 그 수를 count 하는 코드

origin_str = str(input("input your data: "))
slice_list = []
result = ""
j = 0

for i in range(1, len(origin_str)):
    if origin_str[i - 1] != origin_str[i]:
        slice_list.append(origin_str[j:i])
        j = i

slice_list.append(origin_str[j:])

for k in range(len(slice_list)):
    result += f"{slice_list[k][0]}{len(slice_list[k])}"

input yout data: aaabbcccccca
a3b2c6a1

2019/02/01 23:17

x monciel

user_input = input("압축할 문자열을 입력해주세요 : ")
string = user_input[0]
count = 0
for num in user_input:
    if num == string[-1]:
        count += 1
    else:
        string += str(count) + num
        count = 1
string += str(count)
print(string)

2019/02/15 16:44

김상민

while True :
    case = input("입력 : ")
    if case == "종료" :
        exit()

    i = 0

    while i < len(case) :
        j = i+1
        while True :
            if (j<len(case) and case[i] == case[j]) :
                j+=1
            else :
                break
        print(case[i] + str(j-i), end='')
        i += j-i
    print('')

2019/02/15 17:17

동동

my_str = input("압축할 문자열을 입력하세요: ") #abcccddaa
current_chr=my_str[0]
count=1
result=my_str[0]

for i in range(1,len(my_str)):
    if current_chr==my_str[i]:
        count+=1
    if current_chr!=my_str[i]:
        current_chr=my_str[i]
        result = result + str(count) + my_str[i]
        count=1
    if i==len(my_str)-1:
        result += str(count)

print(result)

2019/02/18 15:30

var input = 'aaabbcccccca';
var count = 1, tmp = '';

for (var i = 0; i < input.length; i++) {
    if (input[i] === input[i + 1]) {
        count++;
    } else {
        tmp += input[i] + count;
        count = 1;
    }
}
console.log(tmp);



2019/02/18 19:09

이계민

data = input("문자열 입력 : ")
cnt = 0
last = data[0]
for i, letter in enumerate(data) :
    if letter != last :
        print("%s%d"%(last, cnt), end='')
        if (i + 1) != len(data) :
            last = letter
            cnt = 1
        else :
            print("%s%d"%(letter, 1))
    else :
        cnt += 1
        if (i + 1) == len(data) :
            print("%s%d"%(last, cnt))

2019/02/21 23:30

좋은나쎔

while True:
    string=input("input string: ")
    result=string[0]
    count=1
    for i in range(1,len(string)):
        if string[i]==string[i-1]:
            count+=1
        else:
            result+=str(count)+string[i]
            count=1
    result=result+str(count)

    print(result)



2019/02/26 16:00

ykleeac

def compress(string):
    cnt = 1
    sol = ""
    answer =""
    string = string +'*'
    for i in range(len(string)-1):
        if string[i] == string[i+1]:
            cnt += 1
        else:
            answer = string[i] + str(cnt)
            cnt = 1
            sol += answer
    return sol

2019/02/26 23:36

dodoman

x = 'aaabbcccccca'

def letter_press_dict(x):
    result = dict()
    i=0
    result[(x[0],i)]=1
    for k in range(1,len(x)) :
        if x[k]==x[k-1]:
            result[(x[k-1],i)]+=1
        else:
            i+=1
            result[(x[k],i)]=1

    return result

def letter_press(x):
    result = ''
    for key,val in letter_press_dict(x).items():
        result = result+key[0]+str(val)
    return result

letter_press(x)

2019/03/22 10:14

한상준

s = 'aabcccaaaaas'

result = s[0] 
count  = 0   

for st in s:
    if st == result[-1]:  
        count += 1
    else:
        result += str(count) + st
        count = 1
result += str(count)

print result


2019/03/23 02:03

김성근


def ZIP(code):

    code +=" "
    recode = []
    point = 0

    for i in range(len(code)-1):
        if code[i] != code[i+1]:
            recode.append(code[point])
            recode.append(str(i+1-point))
            point = i+1

    return ''.join(recode)

2019/04/22 19:04

Studying Man

def zip(s, r='', idx=1):
    if idx == len(s):
        print(r + s[0] + str(idx))
        return
    if s[idx-1] == s[idx]: zip(s, r, idx+1)
    else: zip(s[idx:], r + s[0] + str(idx), 1)
>>> zip('aaabbcccccca')
a3b2c6a1

2019/05/01 14:04

messi

def ass(S,ANS):
    if len(S)==1:
        return ANS+S[0]+'1'
    elif len(S)==S.count(S[0]):
        return ANS+S[0]+str(len(S))

    for i in range(len(S)-1):
        if S[i]!=S[i+1]:
            ANS+=S[0]+str(i+1)  
            return ass(S[i+1:],ANS)

print(ass(input(),''))

처음에 그냥 단순히 중복되는 문자들을 세어내는 단순한 문제인줄 알았더니, 자세히 문제를 읽어보니 그것이 아니었군요.^^

2019/05/06 23:01

암살자까마귀

data = input()
cnt = 0
result = data[0]

for i in data:
    if i == result[-1]:
        cnt += 1
    else:
        result += str(cnt) + i
        cnt = 1

result += str(cnt)

print(''.join(result))

2019/06/24 12:20

파이썬주니어

def prob():
    x = input()
    temp = x[0]
    cnt = 1
    res=''
    for i in range(1,len(x)):
        if temp == x[i]:
            cnt += 1
        else:
            res += (temp + str(cnt))
            cnt = 1
            temp = x[i]
    res += (temp + str(cnt))
    print(res)    

2019/08/10 11:24

최재학

#include <stdio.h>

int main(void)
{
    char stri[1000];
    int up = 1;
    int foc = 0;
    scanf("%s",stri);
    while(stri[foc] != '\0')
    {
        if(stri[foc] == stri[foc+1])
            up++;
        else
        {
            if(up != 1)
            {
                printf("%c%d",stri[foc],up);
                up = 1;
            }
            else
                printf("%c",stri[foc]);
        }
        foc++;
    }
    return 0;
}

2019/08/10 22:36

RADEAN STUDIO


string = input('Input the string \n')
new_string = last_str = ''
count: int = 0
for s in string:
    if last_str == s:
        count += 1
    else:
        if count != 0:
            new_string += str(count)
        last_str = s
        new_string += s
        count = 1

new_string += str(count)
print(new_string)

2019/08/11 22:24

불나방

java

import java.util.Scanner;

public class q1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("문자열을 입력하세요");
        String str = sc.next();
        char word = str.charAt(0);
        int stack = 1;
        for(int i = 1; i<str.length(); i++){
            if(word==str.charAt(i)){
                stack++;
                word = str.charAt(i);
            }
            else{
                System.out.print(String.valueOf(word)+stack);
                stack=1;
                word = str.charAt(i);
            }
        }
        System.out.print(String.valueOf(word)+stack);
    }
}       

2019/08/13 14:52

용 빈

C#

class Program
    {
        // 문자열을 입력받아서, 같은 문자가 연속적으로 반복되는 경우에 그 반복 횟수를 표시하여 문자열을 압축하기.
        // 입력 예시: aaabbcccccca
        // 출력 예시: a3b2c6a1

        static void Main(string[] args)
        {
            string str = "aaabbcccccca";
            string result = "";
            char cur_s = ' ';
            int n = 1;

            for (int i = 0; i < str.Length; i++)
            {
                if (cur_s != str[i])
                {
                    if (cur_s != ' ')
                        result = result + cur_s.ToString() + n;
                    cur_s = str[i];
                    n = 1;
                }
                else
                {
                    n++;
                }
            }

            result = result + cur_s.ToString() + n;

            Console.WriteLine(result);

        }
    }

2019/08/21 10:51

류원형

ef cum_str(s):
    res=''; i=0; ch=''
    for c in s:
        if ch=='':
            ch=c; i=1
        elif c!=ch:
            res+=ch+str(i)
            ch=c; i=1
        else:
            i+=1
    res+=ch+str(i)        
    return res

s=input('Enter the string: ')
print(cum_str(s))

2019/08/26 13:24

돔돔

a=list(input("문자열 입력: "))
def check(string):
    result=""
    i=0
    count=0
    b=string[i]
    while i<len(a):
        if b !=string[i]:
            result=result+b+str(count)
            b=string[i]
            count=0   
        i +=1
        count +=1
    result=result+b+str(count)
    return result
print(check(a))

2019/08/27 18:04

박재욱

_Input=input("string:")         #사용자에게 문자열 입력받음
_strList=list(_Input)           #리스트형태로 만든다( 문자한개한개 비교하기위해)
Output=[]                       #갯수센 문자열 넣을 리스트
count=1                         #알파벳 카운터 초기화

# 사용자가 입력한 문자열들 확인
for n,a in enumerate(_strList):
    if n+1!=len(_strList):              #리스트 끝이아닐때까지만 돌고
        if _strList[n]==_strList[n+1]:  #만약 현재 알파벳이 다음번 알파벳이랑 같으면 카운트+1
            count+=1
            continue

        Output.append((a+str(count)))   #다음거랑 안같으면 Output 리스트에 추가
        count=1                         #카운트 변수 초기화
    else:
        Output.append((a+str(count)))   #마지막이면 그상태로 아웃풋에 입력
print(''.join(Output))




2019/08/30 17:09

Cosu

a = 'aaabbccccccaacccccccccbbbbbbaaaaaa'

def count(string):
    result = ''
    count = 1
    for itr in range(len(string)):
        if string[itr-1] == string[itr]:
            count += 1
        if not string[itr-1] == string[itr]:
            result += string[itr-1] + str(count)
            count = 1
        if itr == len(string)-1:
            result += string[itr-1] + str(count)
    return result

print(count(a))

2019/09/10 16:46

Dreaming Pug

PHP

$str = "aaabbcccccca";

$result = "";
for ($i = 0, $cnt = 0, $arr = str_split($str), $len = count($arr); $i < $len; $i++) {
    $cnt++;
    if (!isset($arr[$i + 1]) || $arr[$i + 1] !== $arr[$i]) {
        $result .= $arr[$i].$cnt;
        $cnt = 0;
    }
}
print_r($result); // a3b2c6a1

2019/09/11 14:26

d124412

inputString = str(input("문자를 입력하십시오 : ")) result = inputString[0] countNumber = 0

for s in inputString: if s == result[-1]:
countNumber += 1 else: result += str(countNumber) + s countNumber = 1 result += str(countNumber)

print(result)

2019/09/12 04:00

김민규

string getStr(string str) { string ret = ""; int cnt = 0; string ch;

for (int i = 0; i < str.length();)
{
    cnt = 0;
    ch = str[i];

    for (int j = i; ; j++)
    {
        if (j == str.length())
        {
            ret += (cnt == 1) ? ch : ch + to_string(cnt);
            i = j;
            break;
        }

        char temp = str[j];

        if (str[i] != temp)
        {
            ret += (cnt == 1) ? ch : ch + to_string(cnt);
            i = j;
            break;
        }
        cnt++;
    }
}
return ret;

}

2019/09/18 15:22

욜로

str = input('input : ')
count = 1
ans = []


for i in range(len(str)):
    if i == len(str)-1: #마지막 문자일경우
        ans.append(str[i])
        ans.append(count)
        break
    elif str[i] != str[i+1]: #앞뒤 글자가 다를경우
        ans.append(str[i])
        ans.append(count)
        count = 1
    else: #앞뒤 글자가 같을경우
        count += 1

for i in ans:
    print(i, end='')

2019/10/07 11:16

후눈

inp, count, result = input("input : "), 0, []
for k in range(0, len(inp)) :
    if inp[k] == inp[k-1] and k != 0 :
        count += 1
    elif k == 0 :
        result.append(str(inp[k]))
        count = 1
    elif inp[k] != inp[k-1] :
        result.append(str(count))
        result.append(str(inp[k]))
        count = 1
result.append(str(count))
print("".join(result))

결과

input : sssseef

s4e2f1

2019/10/10 16:00

GG

import java.util.Scanner;

public class StringCompress {

private String str;

public StringCompress() {

    Scanner scan= new Scanner(System.in);
    System.out.print("입력 : ");
    str=scan.next();
}

public void PrintCompressString() {

    String strs[]=str.split("");

    String temp=strs[0];
    int index=1;
    String result="";

    for (int i=1;i<strs.length;i++) {       
        if(temp.equals(strs[i])) {
            index++;
        }else {
            result+=temp+String.valueOf(index);
            temp=strs[i];
            index=1;
        }
    }
    result+=temp+String.valueOf(index);
    System.out.println("출력 : "+result);
}

}

2019/10/17 09:08

채희범

Python 3.7

a = input()
rslt = [a[0], 0]
for i in a:
    if i == rslt[-2]:
        rslt[-1] += 1
    else: rslt += i, 1
print("".join(map(str, rslt)))

2019/10/17 15:41

AY

class Solution(object):
    def transform(self, str):
        ret = ""
        if str == ret:
            return ret
        t_ch = str[0]
        cnt = 1
        for ch in str[1:]:
            if t_ch == ch:
                cnt += 1
            else:
                ret = ret + t_ch + '%d'%cnt
                t_ch = ch
                cnt = 1
        ret = ret + t_ch + '%d'%cnt
        return ret

if __name__ == '__main__':
    sol = Solution()
    test_set = ["aaabbbcccc", "abc", "bcccbcccc"]

    for test in test_set:
        print sol.transform(test)

2019/11/06 04:55

RumbleBang

앞쪽 풀이 과정을 보고 진행 하였습니다...ㅠㅜ


def Compress(data):
    ini_data = data[0]
    count =0 
    for i in data:
        if ini_data[-1] == i :
            count += 1         
        else :
            ini_data +=  str(count) + i
            count = 1
    ini_data += str(count)
    print(ini_data)

Compress("aaabbcccccca")

2019/11/12 22:40

semipooh

import java.util.*;
public class 문자열압축하기 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String[] lines = scan.nextLine().split("");
        StringBuffer line = new StringBuffer();
        int count = 1;
        for(int i=0; i<lines.length; i++) {
            try {
             if(lines[i].equals(lines[i+1])) {
                 count++;
             }
             else {
                 line.append(lines[i]);
                 line.append(count);
                 count = 1;
             }
            }catch(ArrayIndexOutOfBoundsException e) {
                if(lines[i].equals(lines[i-1])) {
                    line.append(lines[i]);
                    line.append(count);
                    break;
                }
                else {
                    line.append(lines[i]);
                    line.append("1");
                }
            }
        }
        System.out.println(line);
    }
}

2019/11/24 18:42

big Ko

파이썬 3.6 입니다

def string_compress(s):
    compressed = s[0]
    count = 0

    for ch in s:
        if ch == compressed[-1]:
            count += 1
        else:
            compressed += str(count) + ch
            count = 1
    compressed += str(count)
    return compressed

print(string_compress("aaabbcccccca"))

2019/11/27 16:06

vkospi

number=0
for i in word:
  if number==0:
    print(i, end='')
    count=1
  elif word[number]==word[number-1]:
    count+=1
  else:
    print(str(count)+i, end='')
    count=1
  number+=1
  if number==len(word):
    print(str(count))

어려운 문법 잘 몰라서 쉽게 했어요. 아 input을 안했구나 ㅎㅎ 설명 드리자면 number는 몇번째 알파벳인지 카운트 count는 동일한게 몇번째인지 카운트 i는 word의 알파벳입니다.

2019/11/29 14:36

개구리 컴IT KermIT Da Frog

파이썬입니다.

a = str(input('문자열를 입력하시오: '))
result = a[0]
count = 0

for i in a:
  if i == result[-1]:
    count +=1
  else:
    result += str(count) + i
    count = 1
result += str(count)

result

2019/12/22 22:26

Sean

st = input("문자열을 입력하세요 : ")

result = st[0]
count = 1

for i in range(1, len(st)):
    if st[i] == result[-1] and i == len(st) - 1:
        result = result + str(count+1)

    elif st[i] == result[-1]:
        count += 1

    else:
        result = result + str(count) + st[i]
        count = 1
print(result)

미흡하지만 올려봅니다

2020/01/24 14:39

김진우

N,Nformer, Nint,Nfinish = list(input()),"",1,list()
for i in range(len(N)):
    if Nformer == N[i]:
        Nint += 1
    elif Nformer != N[i]:
        if Nformer != "":
            Nfinish.append([Nformer,Nint])
            Nint = 1
    Nformer = N[i]
Nfinish.append([Nformer,Nint])
print(Nfinish)

2020/02/01 15:12

BlakeLee

def str_com(string):
    print(string,end='\n')
    size = len(string)
    str_zip= ""

    ch = ""
    if size > 0 : ch = string[0]
    count = 1
    for i in range(0, size):
        if(size == 1) :
            str_zip +=string[0]+str(1)
            break
        elif (size <=0 ):
            break
        if(i== size-1) :
            if string[i-1] == string[i] :
                str_zip +=ch+str(count) 
            else :
                str_zip +=string[i]+str(1)
            break

        if(string[i] == string[i+1]):
            count += 1
            ch = string[i]

        elif string[i] != string[i+1]:
            str_zip +=ch+str(count) 
            ch = string[i+1]
            count = 1

    print(str_zip)
str_com("")   
str_com("aaabbccccdeeahhg")
str_com("a")
str_com("abcdefggg")
str_com("하늘과나무나무좋아!!!")


결과:


aaabbccccdeeahhg
a3b2c4d1e2a1h2g1
a
a1
abcdefggg
a1b1c1d1e1f1g3
하늘과나무나무좋아!!!
하1늘1과1나1무1나1무1좋1아1!3

2020/02/10 22:15

maluchi

파이선 3.8

word = input('입력 예시: ')
x = 0
count = 0
for i in range(len(word)):
    if word[x]==word[i]:
        count += 1
        if i == len(word)-1:
            print('{}{}'.format(word[x],count), end='')
    else:
        print('{}{}'.format(word[x],count), end='')
        x=i
        count = 1
        if i == len(word)-1:
            print('{}{}'.format(word[x],count), end='')

2020/02/17 22:10

카레맛카레

파이썬 형식입니다

i = input('문자를 입력하세요 : ')
J = {}
K = ''
while True:
    if i != '':
        I = i

        i = '%s' % i.lstrip('%s' % i[0])

        J.setdefault('%s' % I[0], '%s' % ((len(I)) - len(i)))

        K = K + (list(J.keys())[0]) + (list(J.values())[0])
        J.pop('%s' %(list(J.keys())[0]))
    elif i == '':
        break

print(K)

2020/03/10 15:55

WooChan Jeon

#include <iostream>
#include <list>
#include <string>
using namespace std;
/*
문자열을 입력받아서, 같은 문자가 연속적으로 반복되는 경우에 그 반복 횟수를 표시하여 문자열을 압축하기.

입력 예시: aaabbcccccca
출력 예시: a3b2c6a1
*/
void Func(string s) {
    cout << s << " -> ";
    list<char> l;
    list<char> n;
    int count = 1;
    for (int i = 0; i < s.length(); i++) {
        l.push_back(s[i]);
    }

    list<char>::iterator iter = l.begin();
    list<char>::iterator iter2 = iter;
    ++iter2;
    while(1){
        if (iter2 == l.end()) { n.push_back(count + '0'); break; }
        if (*iter == *iter2) { ++count; }
        else { n.push_back(count +'0'); count = 1; }
        ++iter, ++iter2;
    }
    l.unique();
    list<char>::iterator nter = n.begin();

    for (iter = l.begin(); iter != l.end(); iter++, nter++)
        cout << *iter << *nter;
    cout << endl;
}

int main() {
    Func("aaabbcccccca");
}

2020/03/23 16:33

++C

a=str(input('input.....'))
cnt,tmp=1,a[0]
for i in range (1,len(a)):
    if tmp!=a[i]:
        print (tmp+str(cnt),end='')
        cnt,tmp=1,a[i]
    else:
        cnt+=1
    if i== len(a)-1:
        print (tmp+str(cnt))

2020/04/14 09:55

Buckshot

<결과> input.....aaaassaeee a4s2a1e3 input.....aaabbcccccca a3b2c6a1 - Buckshot, 2020/04/14 09:55
def zip(s):
    result = s[0]
    count = 1
    for i in range(1, len(s)):
        if s[i-1] == s[i]:
            count += 1
        else:
            result += str(count)
            result += s[i]
            count = 1

    result += str(count)

    print(result)


zip('alaabddbccccccca')

2020/04/17 20:59

ptjddn95

파이썬 3.8로 작성했어어요. 간결하게 코드짜기가 어렵네요 모두 좋은 일욜 되시고 화이팅입니다!!

def compress_words(wrd): #오류 처리 방법을 위한 함수 정의
    wrds_len=len(words) #
    count=1
    nw_words=''
    for i in range(wrds_len):
        try: # i가 그 다음값과 같은 경우 count를 하나 더 해줌
            if words[i]==words[i+1]:
                count+=1
            else: #i가 그 다음값과 다른 경우 count와 i번째 문자를 압축 값에 더해줌
                number=str(count)
                nw_words=nw_words+words[i]
                nw_words=nw_words+number
                count=1
        except:# i가 range를 넘어가서 오류가 생기는 경우, 즉 마지막 경우에는 count값과 i번째 문자를 압충 값에 더해줌.
            number=str(count)
            nw_words=nw_words+words[i]
            nw_words=nw_words+number
    print(nw_words)

words=input("문자열을 입력하시오")
compress_words(words)

2020/04/19 04:59

Dongsuk Kim

Str=input("입력 : ")
count=1
for i in range(len(Str)-1):
    if Str[i]==Str[i+1]:
        count+=1
    else:
        print("{}{}".format(Str[i-1],count),end="")
        count=1
print("{}{}".format(Str[len(Str)-1],count))

2020/04/26 21:22

kim center

def zip(data):
    cnt = 1
    encoded = ''
    for s in range(1, len(data)):
        if data[s] == data[s - 1]:
            cnt += 1
        else:
            encoded += data[s-1] + str(cnt)
            cnt = 1
        if s == len(data) - 1:
            encoded += data[s] + str(cnt)
    return encoded

def main():
    strings = 'aaabbcccccca'
    print(zip(strings))         #a3b2c6a1
if __name__ == '__main__':
    main()

2020/04/28 18:43

Hwaseong Nam

def str_comp(s, converted = ""):
    if not s: 
        return converted
    elif not converted:
        return str_comp(s[1:], f"{s[0]}1")
    else:
        last = converted[-2]
        count = int(converted[-1])
        if s[0] == last:
            return str_comp(s[1:], converted[:-1] + str(count + 1))
        else:
            return str_comp(s[1:], converted + f"{s[0]}1")

2020/05/10 22:16

김준혁

s = 'aaabbbcccddd'

result = s[0]  
count  = 0   

for i in s:
    if i == result[-1]:  
        count += 1
    else:
        result += str(count) + i
        count = 1
result += str(count)

print(result)

2020/05/13 22:52

Money_Coding

파이썬3입니다.

iString = 'aaabbcccccca'
cString = iString[0]
count = 0

for x in iString :
    if x == cString[-1] :
        count += 1
    else :
        cString += str(count) + x
        count=0

print(cString)

2020/06/23 08:43

누마루

case='aaabbcccccca'
result=''
count=1
for i in range(len(case)-1):    
    if case[i] == case[i+1]:
        count+=1
    else:
        result+=case[i] + str(count)
        count=1
        continue
if case[len(case)-2] == case[len(case)-1]:
    result+=case[len(case)-1] +str(count)
else:
    result+=case[len(case)-1] +'1'

print(result)

2020/06/25 17:32

김찬렬

동일 풀이가 많지만 올려봅니다.

'''
문자열을 입력받아서, 같은 문자가 연속적으로 반복되는 경우에 그 반복 횟수를 표시하여 문자열을 압축하기.

입력 예시: aaabbcccccca

출력 예시: a3b2c6a1
'''

input = "aaabbcccccca"
output = input[0]
count = 0
for c in input[1:]:
    if(output[-1] == c):
        count+=1
    else:
        output += str(count) + c
        count = 1
output += str(count)
print(output)
# result : a2b2c6a1

2020/07/06 13:42

심형관

public class StringZip {
   public static void main(String... strings) {
       System.out.println(zip("aaaabbbbccccddddeeeeffff"));
       System.out.println(zip("abcc"));
       System.out.println(zip("ab"));
       System.out.println(zip("a"));
   }

   public static String zip(String str) {
       int count = 1;
       char ch = str.charAt(0);
       StringBuffer buffer = new StringBuffer();
       for (int i = 1; i < str.length(); i++) {
           if (str.charAt(i) == ch) {
               count++;
           } else {
               buffer.append(ch).append(count);
               ch = str.charAt(i);
               count = 1;
           }
       }
       buffer.append(ch).append(count);
       return buffer.toString();
   }
}


2020/07/14 23:38

불나방

struct Current {
    var currentChar:String
    var currentCnt:Int
}

func solution(inputStr:String) {
    let inputStrArr:Array<Character> = Array(inputStr)
    var currentState:Current = Current(currentChar: "", currentCnt: 0)
    var resultStr:String = ""
    for i in 0..<inputStrArr.count {
        if String(inputStrArr[i]) == currentState.currentChar {
            currentState.currentCnt += 1
            continue
        }
        else {
            if currentState.currentChar != "" {
                resultStr = resultStr + currentState.currentChar + "\(currentState.currentCnt)"
            }
            currentState.currentCnt = 1
            currentState.currentChar = String(inputStrArr[i])
        }
    }
    resultStr = resultStr + currentState.currentChar + "\(currentState.currentCnt)"
    print("\(resultStr)")
}

solution(inputStr: "aaabbcccccca")

2020/07/26 20:52

이한위

word = input("> ")

def countword(word):
    L = [i for i in range(len(word)) if word[i-1]!=word[i]]
    M= list()
    for i in range(len(L)):
        if i>0:
            M.append(word[L[i-1]]+str(L[i]-L[i-1]))
        elif word[0]==word[-1]:
           M.append(word[0]+str(L[0]))
    M.append(word[-1]+str(len(word)-L[-1]))
    for j in M:
      print(j, end='')

countword(word)

2020/07/29 00:30

김병관

s = 'aaabbcccccca'
cur_char = None
cnt = 0
for c in s:
    if cur_char != c:
        if cnt >= 1:
            print(cnt, end='')
        print(c, end='')
        cur_char = c
        cnt = 1
    else:
        cnt += 1
print(cnt, end='')

2020/08/18 16:17

Chang-Hoon Lee

public class test5 {
    public static void main(String[] args) {
        String input = "aaabbbcccddddeeee";

        String result = "";
        int num = 1;
        char temp;

        for (int a = 0; a < input.length(); a++) {
            temp = input.charAt(a);
            if(a == input.length() - 1) {
                if(temp == input.charAt(a - 1)) {
                    result = result + temp + num;
                    num = 1;
                }
            } else {
                if(temp == input.charAt(a + 1)) {
                    num++;
                } else if (temp != input.charAt(a + 1)) {
                    result = result + temp + num;
                    num = 1;
                }
            }
        }

        System.out.println(result);
    }
}

2020/09/15 18:31

nazunamoe

public static void main(String[] args) {        

        String word = "aaabbcccccca";
        char[] alphabet = word.toCharArray();
        int count = 1;

        for(int i=0; i<alphabet.length-1; i++) {
            if(alphabet[i] == alphabet[i+1]) {
                count++;
            }else{
                System.out.printf("%s%d\n",alphabet[i] ,count);
                count = 1;
            }
            if((i+1)==alphabet.length-1) System.out.printf("%s%d\n",alphabet[i+1] ,count);
            }   
        }   

2020/10/06 19:09

B A

자바입니다,

import java.util.Scanner;

public class String_Press {

    static int count =1;

    public static String p(String a) {

        String[] input = a.split("");
        String ret = input[0];
        int i=0;
        while(true) {
            if(input[i].equals(input[i+1])) {
                count++;
                i++;
                if(i==input.length-1) {
                    ret+=count;
                    break;
                }
            }
            else {
                ret+=count + input[i+1];
                i++;
                count =1;
                if(i==input.length-1) {
                    ret+=count;
                    break;
                }
            }
        }
        return ret;
    }   

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        System.out.println(p(sc.nextLine()));

        }

2020/10/15 13:35

ᆞᄉ

data='aaabbcccccca'

encoded=''

count=1
for i in range(1,len(data)):
    if data[i]==data[i-1]:
        count+=1
    else:
        encoded+=data[i-1]+str(count)
        count=1
    if i==len(data)-1:
        encoded+=data[i]+str(count)
print(encoded)

2020/11/03 23:43

안녕하세요

package codeDojang;

import java.util.Scanner;

public class Prac {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine(), anw="";
        int cnt = 1;
        for (int i = 0; i < str.length()-1; i++) {
            if(str.charAt(i)==str.charAt(i+1)) {    //같은 문자
                cnt++;
            }
            else {  //다른 문자
                anw += str.charAt(i)+(cnt+"");
                cnt=1;
            }

        }
        System.out.println(anw+str.charAt(str.length()-1)+"1");


    }
}


마지막문자가 안나와서 어거지로 삽입했는데 너무 더럽,,

2020/11/17 13:13

yijun kim

def compress(s):
    temp = [0]
    abc = [0]
    for i in range(0,len(s)-1):
        if s[i] != s[i+1]:
            temp.append(i+1)
            abc.append(s[i])
    if len(s)-1 == temp[-1]:
        temp.append(len(s))
        abc.append(s[len(s)-1])
    for i in range(0,len(temp)-1):
        print(abc[i+1] + str(temp[i+1]-temp[i]), end='')


compress("aaabbcccccca")

2020/11/25 18:06

김우석

파이썬 3.7 입니다.
다른 분들이랑 다른 방법으로 해보려고했는데 초보라 그런지 단점이 많습니다.

X = str(input('압축할 문자열을 입력해 주세요.'))
count_dict = {Y: 0 for Y in set(X[:])} # 압축된 문자수 카운트용 dict 생성

for i in X: # 입력받은 문자열에서 반복된 문자들을 dict_value으로 카운트
    count_dict[i] += 1

dic_list = []  # count_dict.items()를 '키 값 키 값 키 값'형태로 join하기위한 리스트 생성 
for key, val in count_dict.items():
    dic_list.append(str(key))
    if val == 1:
        dic_list.append('') # 한 번만 입력된 문자는 숫자를 붙이지 않기 위함
    else:
        dic_list.append(str(val)) # join을 하기위해 str형으로 변환

result = ''.join(dic_list)

print(result)

2020/11/28 16:38

최병찬

input_numbers = "aaaaabbbbbbbccccccc"

start = None
result = []
count = 1

for (idx, num) in enumerate(input_numbers):
    if num != start:
        start = num
        result.append(start)
        count = 1
    else:
        count += 1
        try:
            if num != input_numbers[idx + 1]:
                result.append(str(count))
        except:
            result.append(str(count))

print(''.join(result))

2020/12/05 20:47

Junghan Shin

a = input('문자열을 입력하세요. :') # ex) aaabbcccccca
b = [a[0]]
cnt = 0

for i in range(len(a)):
    if a[i] == b[-1]:
        cnt += 1
    else:
        b.append(str(cnt))
        b.append(a[i])
        cnt = 1
b.append(str(cnt))

print('압축된 문자열 :', ''.join(b))

파이썬으로 작성했습니다.

2020/12/24 11:40

임준혁

def alzip(strings):

  for_answer=[]

  count=1

  for i in range(0,len(strings)-1,1):

    word=strings[i]

    if strings[i]==strings[i+1]:

      count+=1

    else:

      for_answer.append(word)

      for_answer.append(str(count))

      count=1

    if strings[i]!=strings[i+1] and i+1==len(strings)-1:

      for_answer.append(strings[i+1])

      for_answer.append(str(1))

  if i==len(strings)-2 and strings[i]==strings[i+1]:

    for_answer.append(word)

    for_answer.append(str(count))

  print("".join(for_answer))

alzip('aaabbcccccc')

2020/12/31 16:19

전준혁

A= 'aaabbccccccaa'


i=0
t=0

while i<(len(A)-1):
    if A[i]==A[i+1]:
        t+=1
        if i==(len(A)-2) and A[i] == A[i+1]:
            print(A[i]+str(t+1))
    else:
        print(A[i]+str(t+1),end='')
        t=0 
        if i==(len(A)-2) and A[i] != A[i+1]: 
            print(A[i+1]+str(1))
    i+=1

아직 초보라 그런지 제 풀이가 초라해보이네요..

2021/01/29 22:39

fox.j

def ziper(text):
    result = text[0]
    count = 0

    for aa in text:
        if aa == result[-1]:
            count += 1
        else:
            result += str(count) + aa
            count = 1
    result += str(count)

    return print(result)

ziper('aaabbcccccca')

2021/02/02 08:34

DSHIN

str1=input()

re=str1[0]
count=0

for i in str1:
  if i == re[-1]:
    count+=1
  else:
    re= re+str(count)+i
    count=1

re=re+str(count)

print(re)

2021/02/02 22:51

장래희망파이썬마스터

    const ary = prompt('입력','').split('');
    let cnt =1, result=''; 
    for(let i=0;i<ary.length;i++){
        if(ary[i]==ary[i+1]){
            cnt++
        }else{
            result+=ary[i]+cnt;
            cnt=1;
        }
    }
    console.log(result)

2021/02/08 10:14

wldus

a = input()
b = {}

for i in a:
    if i not in b:
        b[i] = 1
    else:
        b[i] += 1
print(b)

2021/02/13 15:52

pathworker

word = input("")
word_s = sorted(set(word))
word_c = ''

for s in word_s:
    word_c += (s + str(word.count(s)))
print(word_c)

2021/02/15 16:23

asdfa

s = 'aaabbcccccca'

result = []
count = 0
for x in s:
    if len(result) == 0:
        result.append(x)
        count = 1
    elif not x == result[len(result)-1]:
        result.append(count)
        result.append(x)
        count = 1
    elif x == result[len(result)-1]:
        count += 1

result.append(count)

print(''.join(map(str,result)))

2021/02/20 01:20

­장태호 / 학생 / 원자핵공학과

def compress(txt):
    """문자열 압축하기"""
    txt_lst = [i for i in str(txt)]
    cnt = 1
    for i in range(len(txt_lst)):
        if i < (len(txt_lst)-1) and txt_lst[i+1] == txt_lst[i]:
            cnt += 1
        else:
            print(txt_lst[i]+str(cnt), end=' ')
            cnt = 1

txt = input('압축할 문자를 입력하세요.: ')
compress(txt)

2021/04/30 14:03

bravesong

a=input('문자열을 입력하시오:')
a=list(a)
count=1
b=''
for i in range(len(a)):
    if i<len(a)-1:
        if a[i]==a[i+1]:
            count+=1
        else:
            b+=a[i]+str(count)
            count=1

    else:
        b+=a[i]+str(count)

2021/05/17 20:33

이정엽


``````{.java}
public class RunLength {
    public static void main(String[] args) {

        String zip ="aaabbcccccca"; 

        int count = 1;

        for(int i = 0; i < zip.length()-1; i++) {
            if(zip.charAt(i) == zip.charAt(i+1)) { //다음 단어와 같을때
                    count += 1;
                if(i == zip.length()-2) {
                    System.out.print(zip.charAt(i+1)+String.valueOf(count)); // 마지막 값이 같을때 
                    }
            }else{ // 단어가 다를때
                System.out.print(zip.charAt(i)+String.valueOf(count)); // 이전에 값 출력
                count = 1;
                if(i == zip.length()-2) {
                    System.out.print(zip.charAt(i+1)+String.valueOf(count)); // 마지막값 전과 마지막값이 다를때
                }
            }
        }
    }
}

2021/05/28 15:06

박준영

ip = 'aabbbbssbssa'
ip1=''
s=0
for i in range(len(ip)+1):
    if ip[i:i+1]==ip[i+1:i+2]:
        s +=1
    else :
        ip1 += ip[i]+str(s+1)
        s = 0
print(ip1)

2021/05/31 10:48

약사의혼자말

from itertools import groupby
def solution(s):
    answer=''
    for k, g in groupby(s):
        answer += (k+str(len(''.join(g))))
    return answer

2021/06/02 14:44

최태호

python 3.9.5입니다.

string = input('문자열을 입력하세요. ')
chr = string[0]
times = 0
result = ''

for c in string:
    if chr == c: times += 1
    else:
        result += chr
        result += str(times)
        times = 1
        chr = c
result += chr
result += str(times)

print(result)

실행 결과입니다.

문자열을 입력하세요. aaabbcccccca
a3b2c6a1

2021/06/25 10:42

이준우

def counting(n):
 count = 1
 result = ''
 n = n + '\0'
 for i in range(1,len(n)):
     if n[i-1] == n[i]: count += 1
     else:
         result += n[i-1] + str(count) + counting(n[i:])
         break
 return result

print(counting('aaabbcccccca'))

추천풀이 보고 많이 배웠습니다. 재귀함수는 적용이 쉽지 않네요 ㅎㅎ '\0'은 빈 문자열 공백으로 이해하면 될까요?

2021/06/28 22:29

ss2663

#codingdojing_compact string

a = 'aaabbcccccca'
result = ''
gap = a[0]
cnt = 1

for c in a[1:]:
    if c != gap :
        result += (gap+str(cnt))
        gap = c
        cnt = 1
    else:
        cnt += 1

result += (gap+str(cnt)) #last char

print(result)



2021/08/10 17:22

Jaeman Lee

n= input("")
nlist = [x for x in n]
nsetlist = list(set(nlist))
nsetlist.sort()
for i in nsetlist:
    print(i+str(nlist.count(i)),end="")

2021/08/22 14:06

//python

def compress(x):
    result =''
    count=1
    for i in range(1, len(x)):
        if x[i]==x[i-1]:
            count+=1
            if i==len(x)-1:
                result+=x[i]
                result+=str(count)
        else:
            result+=x[i-1]
            result+=str(count)
            count=1
            if i==len(x)-1:
                result+=x[i]
                result+=str(count)
    print(result)

2021/09/05 19:20

trim39r

text = "aaabbccccccaa"
r = 1
print(text[0], end = "")
for i in range(1, len(text)):
    if text[i] == text[i-1]:
        r += 1
    else:
        print(r, end = "")
        print(text[i], end = "")
        r = 1
print(r, end = "")

2021/09/26 16:28

Kim Hangil

s=list(input("문자열을 입력하세요: "))
while len(set(s))>1:
    t=list(s.pop(0))
    while t[0]==s[0]: t.append(s.pop(0))
    print(f'{t[0]}{len(t)}',end='')
print(f'{s[0]}{len(s)}')

어렵네요

2021/10/11 19:29

LSW

def string_short(a):
    c = []
    cnt = 0
    for i in a:
        if cnt == 0:
            c.append(i)
            cnt += 1
        elif i == c[-1]:
            cnt += 1
        elif i != c[-1]:
            c.append(str(cnt))
            c.append(i)
            cnt = 1
    c.append(str(cnt))
    return "".join(c)

if __name__ == '__main__':
    a = input()
    print(string_short(a))

2021/10/13 19:40

서현준

자바스크립트로 작성하였습니다.

자바스크립트에서는 문자열을 배열로 사용할 수 있는 특성이 있어 활용하였습니다.

그리고 꼭 인자에 '문자열'을 입력받아야 합니다.

function compress(x) {
    var start = 0;
    var count = 1;
    var result = "";

    for(i=0; i<x.length; i++) {
        if(x[start] === x[i+1]) count++;
        else {
            result += x[start];
            result += count;
            start = i+1;
            count = 1;            
        }
    }
    console.log(result)       
}

compress('aaabbcccccca')

2021/11/23 17:26

유정효

U = ''
T = input('문자열을 입력하시오.')
count = 1
for i in range(0,len(T)-1):
    if T[i] == T[i+1]:
        count += 1
        if i+1 == len(T)-1:
            U += T[i]
    else:
        U += T[i] + str(count)
        count = 1
        if i+1 == len(T)-1:
            U += T[i+1] + str(count)
print(U)

2021/12/10 17:14

박제준


a = str(input("문자열을 입력하시오"))

arr = []
while True:
    a0 = len(a)
    arr.append(a[0])
    a = a.lstrip(a[0])
    n = a0-len(a)
    arr.append(n)
    if len(a) == 0:
        break

print("".join(map(str,arr)))

파일 압축의 원리라는걸 읽은거 같네요 왼쪽 문자열 자르기 ('lstrip') 함수를 사용했습니다 자르기전 문자열의 길이 - 자른후 문자열의 길이가 문자의 반복회수가 되도록 했어요

2021/12/30 00:41

양캠부부

text = input('문자열을 입력하세요 : ')
print(text)
count = 1
answer = ''
for x in range(len(text)): # text의 길이만큼 반복
    if x+1 != len(text): # x+1이 text의 길이와 같으면 오류가 발생하여 if문으로 구분해주었음.
        if text[x] == text[x+1]: # x번째 글자와 x+1번째 글자가 같으면,
            count += 1 # count를 증가한다.
        else: # x번째 글자와 x+1번째 글자가 같지 않으면,
            answer += text[x] + str(count) # answer에 x번째 글자와 count를 입력하고,
            count = 1 # count를 초기화 시켜준다.
    else: # x+1이 text의 길이와 같으면 가장 마지막 글자 차례이다.
        if text[x] == text[x-1]: # 마지막 글자이므로 뒤가 아닌 앞의 글자와 비교해준다. 비교 값이 같은 경우,
            answer += text[x] + str(count) # answer에 x번째 글자와 count를 입력해준다.
        else: # 마지막 글자와 앞의 글자가 같지 않을 경우,
            answer += text[x] + '1' # 마지막 글자를 입력하고 1을 입력해준다.
print(answer)

2022/01/13 14:48

ㅎㅎ

_input = input()


count = 1
answer = _input[0]
for i in range(1,len(_input)):
    if _input[i] == _input[i-1]: count += 1
    else :
        answer += str(count)
        answer += _input[i]
        count = 1

answer += str(count)
print(answer)


2022/01/25 15:06

강태호

sen = 'aaabbcccccca'
li=[]
li.append(sen[0])
li.append(1)

sen = sen[1:]

while len(sen)>0:
    if sen[0] == li[-2]:
        li[-1] += 1

    else:
        li.append(sen[0])
        li.append(1)

    sen = sen[1:]
str_li = [[x,str(x)][str(x).isdigit()] for x in li]
print(''.join(str_li))

2022/02/14 10:29

로만가

다른 코드를 참고했습니다 :)

package org.javaturotials.ex;
import java.util.*;


public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int count=1;
        String result="";
        String str = sc.nextLine() + " ";
        for(int i=0; i<str.length()-1; i++) {
            if(str.charAt(i)==str.charAt(i+1)) {
                count++;
            }
            else {
                result+=str.charAt(i)+(count + "");
                count=1;
            }
        }
        System.out.println(result);
    }
    }

2022/02/18 20:15

Kkubuck

해결하는데 의의를 두었습니다.

a='aaabbbbaa'
list_a=[] #a를 리스트로
for s in a:
    list_a.append(s)
list_a.append('none')

aa=[]
l=1
for i in range(0,len(a)):
    if list_a[i]==list_a[i+1]:
        l+=1
    else:
        aa.append(list_a[i])
        aa.append(l)
        l=1

for str in aa:
    print(str, end="")

2022/03/02 22:46

코딩초보박영규

def str_zip(str_mat):
    result = [str_mat[0], 0]
    for i in str_mat:
        if i != result[-2]:
            result += [i, 0]
        result[-1] += 1
    print(result)

str_matrix = 'aaabbcccccca'
str_zip(str_matrix)

2022/03/08 16:09

고양이

quiz = "aaabbbcccccca"
count = 1
answer = ""

for idx, i in enumerate(quiz):
    if idx == len(quiz)-1: # i가 마지막일 경우 현재 알파벳 + 카운트를 출력
        answer += f'{i}{count}'
    else: # i가 마지막 숫자가 아닐 때
        if i == quiz[idx+1]: # i랑 i뒤의 알파벳이랑 같으면
            count += 1 # 카운트 1 늘림
        else: # i랑 i뒤의 알파벳이랑 다르면
            answer += f'{i}{count}' # i랑 카운트(첫번째면 1)를 답에 저장
            count = 1 # 카운트 초기화
print(answer) #a3b3c6a1

# 되돌리기
back = ""
for i in range(int(len(answer)/2)): #답 길이의 1/2만큼 반복
    back += answer[::2][i] * int(answer[1::2][i]) # 홀수 인덱스는 알파벳 * 짝수 인덱스는 숫자 곱해서 문자열에 넣기
print(back) #aaabbbcccccca

코린이 입니다. 문제 푸는거 너무 재밌어요ㅋㅋ + 되돌리기 추가했습니당

2022/03/13 17:42

kh ahn

a="aaabbbaacccacbdv" b=0 li=[] su = 0 j=0 for i in a: j += 1 if b==i: su+=1 else: if b!=0: li.append(b) if su!=0: li.append(su) su=0 b=i su+=1 if j == len(a): li.append(b) li.append(su) for i in li: print(i,end="")

2022/04/12 14:11

yunjae

a='aaabbcccccca'
a+=' '
li=[a[0]]
count=0
for i in a:
    if li[-1]==i:
        count+=1
    else:
        li.append(count)
        count=1
        li.append(i)
for i in li:
    print(i,end="")

2022/05/07 19:08

yunjae

inputstr = input()
i = 1
count = 1
result = inputstr[0] + str(count)
while i < len(inputstr) :
  if inputstr[i] == result[-2] :
    count += 1
    result = result[:-1] + str(count)
  else :
    count = 1
    result += inputstr[i] + str(count)
  i += 1
print(result)

문자열의 앞뒤를 비교하기 위한 코드를 짤 때, out of range가 계속 발생해서 어려움을 겪었습니다. 그래서 아예 result를 새롭게 만들고 그것과 문자열을 비교하도록 코드를 짰습니다.

2022/05/09 19:34

나유진

def str_numbering(string):
  result = string[0]
  count = 0
  for s in string:
    if s == result[-1]:
      count += 1
    else:
      result += str(count)+s
      count = 1
  result += str(count)
  return result

2022/05/31 16:03

이승훈

자바로 풀어보았습니다.

import java.util.Scanner;

public class TestMain {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("문자열 입력하시오:");
        String inputData = scan.next();
        String newData = "";
        String character = inputData.substring(0, 1);
        int counts = 1;


        for(int i=1; i<inputData.length(); i++) {           
            if(character.equals(inputData.substring(i, i+1))) {
                counts += 1;
            }else {
                newData += character+String.valueOf(counts);
                counts = 1;
                character = inputData.substring(i, i+1);
            }

            if(i==inputData.length()-1) {
                newData += character+String.valueOf(counts);
            }
        }

        System.out.printf("입력: %s\n\n출력: %s\n", inputData, newData);
    }
}

2022/06/07 18:51

유로

def comp(A):
    result = A[0]
    count = 0
    for i in A:
        if i != result[-1]:
            result += str(count)
            result += i
            count = 1
        else:
            count += 1
    result += str(count)
    return result

2022/06/22 13:18

김시영

word = 'aaabbbbbcscc'
num = 1
new = [word[0]]

for i in range(len(word)-1):
    if word[i] == word[i+1]:
        num += 1
    else:
        new.append(str(num))
        new.append(word[i+1])
        num = 1

new.append(str(num))
print("".join(new))

2022/07/01 09:50

우동훈


aa = input('문자열을 입력하시오 : ')
cc = set(aa)
c = 0
d = []
for ii in cc:
    for iii in aa:
        if ii == iii:
            c+=1
    d.append(ii+str(c))
    c = 0

print(d)

2022/07/11 22:04

Tae Joo

def sol1(s):
    count = 1
    result = ''
    for i in range(1, len(s)):
        if s[i] == s[i-1]:
            count += 1
            if i == len(s)-1:
                result += s[i]
                result += str(count)
        else:
            result += s[i-1]
            result += str(count)
            count = 1
            if i == len(s)-1:
                result += s[i]
                result += str(count)
    return result

ui = input("문자열 입력: ")
print("압축 결과: %s" % sol1(ui))

파이썬 3.8.5

2022/07/11 23:44

Estelle L

초보입니다 처음으로 풀이 올려봅니다

name = str(input('문자열을 입력하세요'))

list = []
text = ''

for i in name: 
    list.append(i) # 문자열의 각 글자를 리스트에 집어넣습니다
    if len(set(list)) == 1: # 같은 글자가 반복되면 집합의 원소의 개수가 1임을 이용합니다
        pass
    else:
        text += list[0] + str(len(list)-1) # 집합의 원소의 개수가 1이 아니면 다른 글자가 나타남을 의미, 기존 반복되던 글자와 반복횟수를 text 에 추가합니다
        list = [i] # 가장 최근에 사용한 글자만 리스트에 남깁니다
text += list[0] + str(len(list)) # 반복문이 끝났을 때 리스트에 남아있는 문자와 그 반복횟수를 text에 추가합니다
print(text)

2022/07/19 20:31

런토토


count = 0
count_list = []

cmd = input("문자열을 입력하시오 :")

cmd_list = list(map(str, cmd))

while True:

    if len(set(cmd_list)) == 1:                                 #cmd_list에 글자가 1개일 경우 실행되는 코드
        for num in range(len(cmd_list)):
            count += 1

        count_list.append(cmd_list[0])
        count_list.append(count)
        del cmd_list

        break

    else:
        for n in range(len(cmd_list)):                          #for문을 이용해 각 글자수의 갯수 파악
            if cmd_list[0] == cmd_list[n]:
                count += 1

            elif cmd_list[0] != cmd_list[n]:
                count_list.append(cmd_list[n-1])                #count_list에 글자의 종류와 갯수를 리스트로 저장
                del cmd_list[:n]
                count_list.append(count)
                count = 0

                break

result = ''.join(str(s) for s in count_list)

print(result)

다른분들이 만든거에 비해서는 굉장히 길고 복잡한거 같네요

2022/07/27 01:08

박종훈

def compStr():
  s = input()
  cnt = 1
  result = ''
  for e in range(len(s)-1):
    if s[e] == s[e+1]:
      cnt += 1
    else:
      result += s[e] + str(cnt)
      cnt = 1
  result += s[-1] + str(cnt)

  return result

2022/07/28 18:17

Charles

str = input("문자열을 입력하세요.")
count=1
for i in range(len(str)):
    if i < len(str)-1:
        if str[i]==str[i+1]:
            count+=1
            continue
    print("{0}{1}".format(str[i], count), end="")
    count=1
print("")

2022/07/28 21:16

김준성

s = "aaabbcccccca" + "\n"
result = ""
cnt = 1
for i in range(1,len(s)):
    if s[i-1] == s[i]:
        cnt += 1
    else:
        result += s[i-1]+str(cnt)
        cnt = 1
print(result)

2022/07/29 15:21

JC YUN

Python. 사용된 함수는 자주 쓰던 것인데, 어떤 함수를 어떻게 쓸 것인가가 더 어려운 과제였습니다. 역시 사고방식을 발전시키는 게 중요한 것 같네요.

def sentence_comp(sentence):
    result=sentence[0] #입력받은 문자열의 첫 번째 요소를 결과에 추가
    count=0 #문자의 반복 횟수를 담을 변수
    for word in sentence:
        if word == result[-1]: #result 변수에 추가된 마지막 요소와 문자를 비교
            count += 1 #값이 동일할 경우 count 변수의 값을 1 증가시킴
        else:
            result += str(count)+word #result 변수의 마지막 값과 다를 경우 count 값을 먼저 result에 추가한 후 새로운 문자 추가
            count = 1 #count 변수는 1로 리셋
    result+=str(count) #가장 마지막의 반복 횟수(count)를 추가하고 마무리
    return result

print(sentence_comp('abbaacdccezzz'))

결과는 a1b2a2c1d1c2e1z3

2022/11/15 10:50

Frye 'de Bacon

s = input() + " "
cnt = 1
for i in range(len(s)-1):
    if s[i] != s[i+1]:
        print(f'{s[i]}{cnt}', end ='')
        cnt = 1
    else: cnt += 1

2022/12/28 09:23

박대선

Python 3.11

[풀이 1]

from re import findall

def solution(string):
    return ''.join(f'{head}{len(tail) + 1}' for head, tail in findall(r'(.)(\1*)', string))

[풀이 2]

def solution(string):
    former, cnt = string[0], 1
    compressed = former

    for latter in string[1:]:
        if former == latter:
            cnt += 1
        else:
            compressed += str(cnt) + latter
            former, cnt = latter, 1

    return compressed + str(cnt)

2023/01/21 22:28

후리가케

s = 'aaabbcccccca'
result = s[0]
count = 0
for string in s:
    print(result)
    if string == result[-1]:
        count += 1
    else:
        result += str(count) + string
        count = 1
result += str(count)
result

import re
s = 'aaabbcccccca'
p = re.compile('(\w)(\\1*)')
p.findall(s)

2023/01/29 13:06

심유진

const func = (arr) => {
  let answer=''
  let count = 1
  let testArr = arr.split('')
  for(let i = 0; i < testArr.length;i ++){
    let curStr = testArr[i]
    if(i + 1 > testArr.legnth){
      answer += curStr
      answer += count
    }else if(testArr[i] === testArr[i + 1]){
      count++
    }else{
      answer += curStr
      answer += count
      count = 1
    }
  }
  return answer
}

2023/02/20 20:17

sooyoung159

ipt = input("input sentence: ")
result = []
prev_char =ipt[0]
count = 0 
for char in ipt:
    if (char == prev_char):
        count += 1
    else :
        result.append(prev_char)
        result.append(str(count))
        count = 1
        prev_char = char

result.append(prev_char)
result.append(str(count))
#print(result)
fin = ''.join(result)
print(fin)

2023/02/25 11:56

제작자

숫자를 구하기 위해서 우선 count를 선언했습니다. result 문자열 slice(-1)을 통해 마지막값과 s[i]값을 비교하고, 만약 같다면 count++을 통해 숫자를 올리고, 다르다면 result에 count를 더한 후 다음 단어(s[i])를 추가했습니다. 그럼 다시 s[i] 반복문이 돌면서 또 result.slice(-1)과 비교하는 형식으로 코드를 구현하였습니다. 마지막 a값에서는 count 값을 별도로 더해주면서 문제가 요구하는 결과값을 출력할 수 있었습니다.

let s = "aaabbcccccca"
let count = 0;
let result = s[0];
for(let i = 0; i < s.length; i++){
    if(s[i] === result.slice(-1)){
        count++;
    } else {
        result += count+ s[i];
        count = 1;
    }
}

console.log(result + count); // a3b2c6a1

2023/03/10 16:25

KUKJIN LEE

strInput=input()

strOutput=""
strCurrent=strInput[0]
strOutput+=strInput[0]+str(strInput.count(strInput[0]))

for i in strInput:
    if i!=strCurrent:
        strOutput+=i+str(strInput.count(i))
        strCurrent=i

print(strOutput)

2023/03/12 13:41

Sol Song

JAVA

import java.util.Scanner;

public class CountText { public static void main(String[] args) { Scanner scn = new Scanner(System.in); System.out.print("문자열 입력 : "); String text = scn.next();

    char a = 'a';
    int count = 0;
    int[] abcCount = new int[26];

        for (int i = 0; i < 26; i++) {
            char temp = (char)(a+i);
            for (int j = 0; j < text.length(); j++) {
                if (temp == text.charAt(j)) {
                    count++;
                }

            }
            abcCount[i] = count;
            if (abcCount[i]!=0) {
                System.out.println(temp+"의 갯수는" +abcCount[i]);                  
            }
            count = 0;
        }
}

}

2023/03/20 14:01

Do Il Yoon

def compress_string(s):
    compressed = ""
    count = 1

    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            count += 1
        else:
            compressed += s[i - 1] + str(count)
            count = 1

    return compressed + s[-1] + str(count) if s else ""

# 입력 문자열 받기
input_str = input("문자열을 입력하세요: ")
compressed_str = compress_string(input_str)
print("출력 결과:", compressed_str)

2023/07/28 14:53

Dongyoon Kim

s = 'aabcccaaaaas'

cnt = 0
for i in range(len(s)):
    cnt += 1
    if i==len(s)-1:
        print('%c%d'%(s[i],cnt), end='')
    elif s[i]!= s[i+1]:
        print('%c%d'%(s[i],cnt), end='')
        cnt = 0

2023/12/05 21:13

insperChoi

def cal(n):
    result = ''
    count = 1
    for i in range(len(n)-1): 
        if n[i] == n[i+1]:  
            count += 1  
        else:
            result += n[i] + str(count)  
            count = 1 
    result += n[-1] + str(count)  
    return result

n = input()
print(cal(n))

2024/05/30 15:28

김현빈

package solution.codingDojang;

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 입력 예시: aaabbcccccca
        String input = "aaabbcccccca";
        // 출력 예시: a3b2c6a1
        String output = "a3b2c6a1";

        // 결과값이 들어갈 변수 선언
        String result = "";

        // 문자열을 입력받아서,
        // input = sc.nextLine();

        // + 문자열을 배열로 담아
        String[] arrStr = input.split("");

        // + 검사할 문자열과 현재 문자열을 검사하기 위해
        // + 검사할 문자열을 담을 변수 선언
        String target = "";

        // 같은 문자가 연속적으로 반복되는 경우에
        // 그 반복 횟수를 표시하여
        // + 반복 횟수를 담은 변수 선언
        int times = 0;
        // 출력 예시: a3b2c6a1
        for (int i = 0; i < arrStr.length; i++) {
//          System.out.println("str: " + arrStr[i] + ", times: " + times + "\nresult: " + result + "\n계속하려면 엔터");
//          sc.nextLine();
            if (i == 0) { // 첫번째 문자는
                target = arrStr[0]; // 바로 담는다
                times++; // 개수를 1 증가
                continue; // 다음 반복으로 이동
            } else { // 두번째 문자부터
                // 이전 문자와 현재 문자를 비교
                if(target.equals(arrStr[i])) { // 같다면
                    times++; // 개수를 1 증가
                    continue; // 다음 반복으로 이동
                } else { // 다르면
                    // 그 반복 횟수를 표시하여
                    // + 결괏값에 붙이기
                    result += target + times;
                    // 검사할 문자열을 현재 문자열로 변경
                    target = arrStr[i];
                    // 반복횟수도 1로 초기화
                    times = 1;
                }
            }
        }
        // 마지막 글자는 붙이는 부분이 없으므로 반복문 밖에 작성
        result += target + times;

        // 문자열을 압축하기.
        // 결괏값과 출력 예시를 비교
        System.out.println("==========");
        System.out.println(result);
        System.out.println("==========");
        System.out.println(output);
        System.out.println("==========");
        System.out.println(result.equals(output));
    }

}

2024/07/07 20:43

이준상

import java.util.Scanner;

public class Coding {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("입력 : ");
        String[] strAry = sc.nextLine().split(""); // 문자열 구분
        String answer = ""; // 출력 변수 생성
        int cnt = 1; // 중복되는 횟수 카운트

        for (int i = 0; i < strAry.length; i++) {
            if (i == strAry.length - 1) { // 배열의 마지막일 때
                if (strAry[i - 1] != strAry[i]) { // 현재 입력 값이 이전 입력 값과 다르면
                    answer += strAry[i] + cnt; // 마지막 입력 값 + 1
                }
            } else if (strAry[i].equals(strAry[i + 1])) { // 현재 입력 값과 다음 입력 값이 서로 같으면
                cnt++; // 중복 횟수 + 1
            } else { // 현재 입력 값과 다른 입력 값이 서로 다르면
                answer += strAry[i] + cnt; // 현재 입력 값 + 중복 횟수
                cnt = 1; // 중복 횟수 초기화
            }
        }
        System.out.println(answer); // 결과 값 출력
    }
}

2024/07/09 22:58

고세정

JAVA입니다.

package 문자열_압축하기;

public class Compress_String {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final String str = "aaabbcccccca";

        char[] chars = str.toCharArray();

        char prev = chars[0]; //이전 문자
        int rep = 0; //반복 횟수
        String result = "";

        for (char c : chars) {
            if(c == prev) {
                rep++;
            }
            else {
                result = result + Character.toString(prev) + Integer.toString(rep);
                rep = 1;
            }
            prev = c;
        }

        result = result + Character.toString(prev) + Integer.toString(rep);

        System.out.println(result);
    }

}

2025/01/15 23:31

박준우


#입력받은 str을 set으로 변환해서 중복을 날리고 set을 리스트로 변환해서 정열하기
def charCount(a):
  s = set(a)
  l = list(s)
  l.sort()
  return l

usrInput = input("문자열을 입력하세요: ")

#문자열에 있는 글자의 리스트
charlist = charCount(usrInput)

#글자를 dict의 key로 이용하고 value는 그 글자가 중복된 숫자로 설정
finalCount = {}

for i in charlist:
  finalCount[i] = usrInput.count(i)

#아웃풋으로 표기할 str 생성
finalout = ""

for i in finalCount:
  finalout += (str(i) + str(finalCount[i]))

print(finalout)

2025/02/21 19:59

Dasol Lee

목록으로