태그 보관물: string

string

가장 짧은 고유 부분 문자열 s입니다. 산출 에서 (연속적인) 하위 문자열로 정확히 한 번

입력

영숫자 문자열 s입니다.

산출

에서 (연속적인) 하위 문자열로 정확히 한 번 발생하는 가장 짧은 문자열입니다 s. 중복 발생은 별개의 것으로 계산됩니다. 길이가 같은 후보가 여러 개있는 경우 모든 후보를 발생 순서대로 출력해야합니다. 이 도전에서, 빈 n + 1문자열은 length의 문자열에서 시간이 발생합니다 n.

문자열을 고려

"asdfasdfd"

빈 문자열은 10 번 발생하므로 고유 한 발생의 후보가 아닙니다. 문자의 각각은 "a", "s", "d", 그리고 "f"그들이 후보 중 하나되지 않도록, 두 번 이상 발생합니다. 부분 캐릭터 "fa""fd"길이 2의 다른 모든 문자열이 두 번 발생하는 동안, 한 번만이 순서대로 발생합니다. 따라서 올바른 출력은

["fa","fd"]

규칙

기능과 전체 프로그램이 모두 허용되며 표준 허점은 허용되지 않습니다. 출력의 정확한 형식은 이유 내에서 유연합니다. 특히 빈 문자열에 대한 출력을 생성하지 않아도되지만 오류를 던지는 것은 불가능합니다. 가장 낮은 바이트 수가 이깁니다.

테스트 사례

"" -> [""]
"abcaa" -> ["b","c"]
"rererere" -> ["ererer"]
"asdfasdfd" -> ["fa","fd"]
"ffffhhhhfffffhhhhhfffhhh" -> ["hffff","fffff","hhhhh","hfffh"]
"asdfdfasddfdfaddsasadsasadsddsddfdsasdf" -> ["fas","fad","add","fds"]

리더 보드

제가 약속 한 언어 별 리더 보드입니다.

답변이 표시되도록하려면 다음 마크 다운 템플릿을 사용하여 헤드 라인으로 답변을 시작하십시오.

# Language Name, N bytes

N제출물의 크기는 어디에 있습니까 ? 당신이 당신의 점수를 향상시킬 경우에, 당신은 할 수 있습니다 를 통해 눈에 띄는에 의해, 헤드 라인에 오래된 점수를 유지한다. 예를 들어 :

# Ruby, <s>104</s> <s>101</s> 96 bytes

<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>site = 'meta.codegolf',postID = 5314,isAnswer = true,QUESTION_ID = 45056;jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)<\\/code><\/pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>



답변

Pyth, 27 26 바이트

&zhfTmf!/>zhxzYYm<>zkdUzUz

여기에서 시도하십시오.

온라인 컴파일러의 버그로 인해 빈 문자열 대소 문자는 명령 행 버전에서만 올바르게 작동합니다 .

온라인 컴파일러의 입력으로 줄 바꿈을 제공하여 버그를 치료할 수도 있습니다.

설명:

                                   z = input(), implicit.
&z                                 Prints empty string if input is empty.
  hfT                              Take the first non-empty list from
     m                  Uz         A list of list of substrings of z, divided by length
                m<>zkdUz           with some shorter strings repeated later, to no effect.
      f                            Where the substrings are filtered on
       !/      Y                   There being 0 occurrences of the substring in
         >z                        The slice of z
           hxzY                    from the character after the first character
                                   of the first occurrence of the substring in z
                                   to the end of z.


답변

파이썬 3 124 123 111 96 바이트

f=lambda s,n=1:[x for x in[s[i:i+n]for i in range(len(s)+1)]if s.find(x)==s.rfind(x)]or f(s,n+1)

왼쪽에서 첫 번째 항목이 오른쪽에서 첫 번째 항목과 같도록 문자열을 찾습니다. +1에서는 range빈 문자열 케이스를 수용하는 것입니다.

이제 파이썬 만 중복 일치 하는 .count()것을 계산 했다면 이것은 조금 짧았을 것입니다.


답변

매스 매 티카, 95 94 79 바이트

Cases[Tally@StringCases[#,___,Overlaps->All],{s_,1}:>s]~MinimalBy~StringLength&

StringCases가능한 모든 하위 문자열을 가져오고 두 번 이상 나타나는 문자열 TallyCases필터링하여 MinimalBy가장 짧은 문자열을 찾습니다.


답변

GolfScript, 44 바이트

:S;-1:x{;S,x):x-),{S>x<}%:^1/{^\/,2=},.!}do`

stdin에서 문자열로 입력을 가져오고 이중 배열 구문으로 출력합니다 (예 🙂 [["b"] ["c"]]. 온라인 데모

해부

:S;          # Store input in S and pop it
-1:x         # Store -1 in x
{            # do-while loop
  ;          #   Pop x the first time and [] every subsequent time
  S,x):x-),  #   Increment x and build an array [0 1 ... len(S)-x]
  {S>x<}%    #   Map that array to [substr(S,0,x) substr(S,1,x) ...]
  :^         #   Store in ^ (to avoid the token coalescing with the next char)
  1/         #   Split by length 1 to iterate over 1-elt arrays rather than strings
  {^\/,2=},  #   Filter to arrays which occur exactly once as a subarray of ^
  .!         #   Duplicate and test emptiness
}do          # end do-while loop: loop if the filtered array is empty
`            # Stringify for output

이것은 빈 문자열 (위의 링크 된 온라인 데모에서 테스트 케이스로 포함)에 특별한 경우가 필요하지 않도록 배열됩니다.


답변

CJam, 52 43 40 바이트

]]q:Q,,{)Q,1$-),f{Q><}:R{R\a/,2=},}%{}=p

입력은 따옴표없는 문자열입니다

설명 :

]]                                       "For empty string input case";
  q:Q                                    "Read the input and store in Q";
     ,,                                  "Take length of input and 0 to length array";
       {                          }%     "Map the above array on this code block";
        )Q                               "Increment the number in the current iteration, L";
         Q,1$                            "Take input's length and copy the above number";
             -)                          "Get upper limit of next loop to get substrings";
               ,f{   }                   "Get 0 to above number array and for each";
                  Q><                    "Get the L length substring at Ith index where";
                                         "I loops from 0 to Q, - L + 1";
                      :R                 "Store this list of substring of length L in R";
                        {R\a/,2=},       "Filter to get unique substrings";
                                    {}=  "Get the first non empty substring array";
                                         "This leaves nothing on stack if all are empty";
                                       p "Print the top stack element. At this point, its";
                                         "Either the first non empty substring array or";
                                         "the ]] i.e. [""] which we added initially";

예:

asdfdfasddfdfaddsasadsasadsddsddfdsasdf

산출

["fas" "fad" "add" "fds"]

여기에서 온라인으로 사용해보십시오


답변

스칼라, 120 바이트

readLine.inits.flatMap(_.tails).toList.groupBy(l=>l).filter(x=>x._2.length<2).map(_._1).groupBy(_.length).minBy(_._1)._2

나는 적어도 이미 트윗에 맞는 140으로 시작했습니다.

(                                        // added for comments
 readLine                                // input
.inits.flatMap(_.tails).toList           // get all substrings of that string
.groupBy(l=>l).filter(x=>x._2.length<2)  // remove substrings that occur more than once
.map(_._1).groupBy(_.length)             // take the substring and group by length
.minBy(_._1)._2                          // take the list of shortest substrings
)


답변

자바 스크립트 (ES6) 109 110

입력 문자열이 영숫자이므로 indexOf 대신 검색을 편집하십시오 . 감사합니다 @IsmaelMiguel

재귀 함수, 길이 1로 시작하여 올라가는 하위 문자열을 찾습니다.

F=(s,n=1,r)=>
s?[...s].map((a,i)=>~s.indexOf(a=s.substr(i,n),s.search(a)+1)?r:r=[...r||[],a])&&r||F(s,n+1):[s]

언 골프 및 설명

 F = function(s, n=1) { // start with length 1
   var i, a, p, r;
   if (s == "") // special case for empty input string
     return [s];
   for (i = 0; i < s.length; i++)
   // for each possibile substring of length n
   // (should stop at s.length-n+1 but going beyond is harmless)
   // Golfed: "[...s].map((a,i)" ... using i, a is overwrittem
   {
     a = s.substr(i, n); // substring at position i
     p = s.search(a); // p is the first position of substring found, can be i or less
     p = s.indexOf(a, p + 1) // p is now the position of a second instance of substring, or -1 if not found
     if (~p) // ~p is 0 if p is -1
     {
       ; // found more than once, do nothing
     }
     else
     {
       r = r || []; // if r is undefined, then it becomes an empty array
       r.push(a); // save substring 
       // Golfed: "r=[...r||[],a]"
     }
   }
   if (r) // if found some substring, saved in r
   {
     return r;
   }
   return F(s, n+1) // recursive retry for a bigger length
 }

FireFox / FireBug 콘솔에서
테스트

;["", "abcaa", "rererere", "asdfasdfd", "ffffhhhhfffffhhhhhfffhhh",
 "asdfdfasddfdfaddsasadsasadsddsddfdsasdf"]
.forEach(x=>console.log(x,F(x)))

산출

 [""]
abcaa ["b", "c"]
rererere ["ererer"]
asdfasdfd ["fa", "fd"]
ffffhhhhfffffhhhhhfffhhh ["hffff", "fffff", "hhhhh", "hfffh"]
asdfdfasddfdfaddsasadsasadsddsddfdsasdf ["fas", "fad", "add", "fds"]