Longest substrings without repeating characters: Difference between revisions

Added Easylang
(Added Easylang)
 
(13 intermediate revisions by 7 users not shown)
Line 11:
{{trans|Python: Some optimisation}}
 
<langsyntaxhighlight lang="11l">F longest_substring2(s)
V max_subs = [s[0.<1]] * 0
V mx = 0
Line 29:
 
V arr = [1, 2, 3, 4, 1, 2, 5, 6, 1, 7, 8, 1, 0]
print(arr‘ => ’longest_substring2(arr))</langsyntaxhighlight>
 
{{out}}
Line 42:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC GetLength(CHAR ARRAY s BYTE start)
BYTE ARRAY tab(256)
BYTE i
Line 106:
Test("thisisastringtest")
Test("")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Longest_substrings_without_repeating_characters.png Screenshot from Atari 8-bit computer]
Line 130:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Longest_Substring is
Line 186:
Test ("thisisastringtest");
Test ("zzzzz");
end Longest_Substring;</langsyntaxhighlight>
{{out}}
<pre>
Line 200:
longest : 'z'
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">lswrc←{
sfx ← ⌽∘,¨,\∘⌽
wrc ← ⊢(/⍨)⍳∘⍴(∧\=)⍳⍨
ls ← ⊢(/⍨)(⌈/=⊢)∘(≢¨)
ls wrc¨ sfx ⍵
}</syntaxhighlight>
{{out}}
<pre> lswrc¨ 'xyzyabcybdfd' 'xyzyab' 'zzzzz' 'a' ''
┌─────────────┬──────┬───────────┬───┬┐
│┌─────┬─────┐│┌────┐│┌─┬─┬─┬─┬─┐│┌─┐││
││cybdf│zyabc│││zyab│││z│z│z│z│z│││a│││
│└─────┴─────┘│└────┘│└─┴─┴─┴─┴─┘│└─┘││
└─────────────┴──────┴───────────┴───┴┘</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">unrepeatableSubstrings: function [s][
result: [["",0]]
 
if zero? s -> return []
if one? s -> return @[s]
 
loop 0..dec size s 'a [
if (a+1) =< dec size s [
loop a..dec size s 'b [
substr: to :string slice s a b
ss: size substr
if and? -> ss >= last maximum result 'x -> last x
-> substr = unique substr [
result: (select result 'x -> ss = last x) ++ @[@[substr, ss]]
]
]
]
]
result: unique map result 'x -> first x
return result
]
 
 
loop ["xyzyabcybdfd", "xyzyab", "zzzzz", "a", ""] 'str ->
print [str "=> longest unrepeatable substring:" unrepeatableSubstrings str]</syntaxhighlight>
 
{{out}}
 
<pre>xyzyabcybdfd => longest unrepeatable substring: [zyabc cybdf]
xyzyab => longest unrepeatable substring: [zyab]
zzzzz => longest unrepeatable substring: [z]
a => longest unrepeatable substring: [a]
=> longest unrepeatable substring: []</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">LSWRC(str){
found := [], result := [], maxL := 0
if (StrLen(str) = 1)
Line 225 ⟶ 277:
result[str] := true
return result
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">db =
(
xyzyabcybdfd
Line 241 ⟶ 293:
}
MsgBox % output
return</langsyntaxhighlight>
{{out}}
<pre>xyzyabcybdfd > [cybdf, zyabc]
Line 250 ⟶ 302:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
// Fills up 'v' with words where w%0 is the start and w%1 is the end
Line 308 ⟶ 360:
example("a")
example("")
$)</langsyntaxhighlight>
{{out}}
<pre>Original string: 'xyzyabcybdfd'
Line 320 ⟶ 372:
Original string: ''
Longest substrings: <empty></pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">LongUniq ← ⌈´⊸=∘(≠¨)⊸/ ∧`∘∊⊸/¨∘↓</syntaxhighlight>
Alternative:
<syntaxhighlight lang="bqn">LongUniq ← ⊢´∘⊔∘(≠¨)⊸⊏ ∊⊸⊐⟜0⊸↑¨∘↓</syntaxhighlight>
Test:
<syntaxhighlight lang="bqn">LongUniq¨ "a"‿""‿"zzz"‿"xyzyab"‿"xyzyabcybdfd"</syntaxhighlight>
{{out}}
<pre>┌─
· ⟨ "a" ⟩ ⟨ ⟨⟩ ⟩ ⟨ "z" "z" "z" ⟩ ⟨ "zyab" ⟩ ⟨ "zyabc" "cybdf" ⟩
┘</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 374 ⟶ 437:
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Original string: "xyzyabcybdfd"
Line 388 ⟶ 451:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <fstream>
#include <set>
Line 455 ⟶ 518:
test1();
test2("unixdict.txt");
}</langsyntaxhighlight>
 
{{out}}
Line 479 ⟶ 542:
Longest substring with no repeats found in 'unixdict.txt': ['mbowel
disgrunt']
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func$[] longstr s$ .
subr maxtest
if len sub$ >= max
if len sub$ > max
max = len sub$
max$[] = [ ]
.
max$[] &= sub$
.
.
s$[] = strchars s$
len empty[] 255
len pos[] 255
pos = 1
while pos <= len s$[]
c = strcode s$[pos]
if pos[c] > 0
maxtest
pos = pos[c] + 1
pos[] = empty[]
sub$ = ""
c = strcode s$[pos]
.
pos[c] = pos
sub$ &= strchar c
pos += 1
.
maxtest
return max$[]
.
for s$ in [ "xyzyabcybdfd" "xyzyab" "zzzzz" "a" "thisisastringtest" "" ]
print longstr s$
.
</syntaxhighlight>
{{out}}
<pre>
[ "zyabc" "cybdf" ]
[ "zyab" ]
[ "z" "z" "z" "z" "z" ]
[ "a" ]
[ "astring" "ringtes" ]
[ "" ]
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: formatting grouping io kernel math sequences sets ;
 
: unique-substrings ( seq n -- newseq )
Line 497 ⟶ 606:
 
"Longest substrings without repeating characters:" print
{ "xyzyabcybdfd" "xyzyab" "zzzzz" "a" "" } [ test ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 509 ⟶ 618:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">dim as string example = "antidisestablishmentarianism is a long word and so is flibbertigibbet."
 
function nrls( t as string ) as string
Line 539 ⟶ 648:
print ">";nrls("abcdefghijklmnopqrstuvwxyz");"<"
print ">";nrls("aaa aeiou uuu");"<"
</syntaxhighlight>
</lang>
{{out}}<pre>
>blishmentar<
Line 548 ⟶ 657:
> aeiou<
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="future basic">
local fn substrings( t as CFStringRef )
int beg, c, f, rpt, max = 0
for beg = 0 to len(t) - 1
rpt = instr( beg+1, t, mid(t, beg, 1), NSCaseInsensitiveSearch )
if rpt < 0 then rpt = len(t)
c = beg + 1
while c < rpt
f = instr(c + 1, t, mid(t, c, 1), NSCaseInsensitiveSearch)
if f < 0 then f = len(t) else if f < rpt then rpt = f
c++
wend
if rpt - beg < max then continue
if rpt - beg > max then max = rpt - beg : mda_clear
mda_add(0) = mid(t, beg, max)
next
print @"\n The string: \"";t;@"\"\n Substring/s: ";
for c = 0 to mda_count(0) -1
print @"\"";mda(c);@"\" ";
next
print
end fn
 
window 1, @"Longest Substring/s Without Repeated Letters"
fn substrings(@"xyzyabcybdfd")
fn substrings(@"thisisastringtest")
fn substrings(@"My spoon is too big.")
fn substrings(@"Rosetta Code")
fn substrings(@"AaAaA")
fn substrings(@"abcdefghijklmnopqrstuvwxyz")
fn substrings(@"aaa aeiou uuu")
fn substrings(@"abcdABCD")
 
handleevents
</syntaxhighlight>
{{out}}
[[File:Longest Substrings without Repeated Letters.png]]
 
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 615 ⟶ 763:
fmt.Printf("Length = %d\n\n", len(longest[0]))
}
}</langsyntaxhighlight>
 
{{out}}
Line 643 ⟶ 791:
 
=={{header|J}}==
Implementation:<langsyntaxhighlight Jlang="j">longnorep=: {{
c=. #y
while. ss=. c ]\ y do.
Line 650 ⟶ 798:
c=. c-1
end.
}}</langsyntaxhighlight>
 
Examples:
 
<langsyntaxhighlight Jlang="j"> longnorep 'xyzyabcybdfd'
zyabc
cybdf
Line 669 ⟶ 817:
ringtes
longnorep 'Thequickbrownfoxjumpsoverthelazydog'
Thequickbrownf</langsyntaxhighlight>
 
This also works on sequences of numbers (though the character representation of the sequences of numbers may contain repeated characters, the represented numbers will not contain repetitions):
 
<langsyntaxhighlight Jlang="j"> longnorep 1 2 3 4 1 2 5 6 1 7 8 1 0
3 4 1 2 5 6
2 5 6 1 7 8</langsyntaxhighlight>
 
=={{header|jq}}==
Line 681 ⟶ 829:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<langsyntaxhighlight lang="jq"># Use a dictionary for speed in case of very long strings
def alluniquehead:
length as $n
Line 711 ⟶ 859:
end)
| .ans;
</syntaxhighlight>
</lang>
'''Test Cases'''
<langsyntaxhighlight lang="jq">"xyzyabcybdfd",
"xyzyab",
"zzzzz",
Line 719 ⟶ 867:
""
| "\"\(.)\" => \"\(maximal_substring_with_distinct_characters)\""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 732 ⟶ 880:
=={{header|Julia}}==
Works on any array, treating a character string as a character array.
<langsyntaxhighlight lang="julia">function alluniquehead(arr)
len = length(arr)
if len > 1
Line 756 ⟶ 904:
println("\"$s\" => ", uarray)
end
</langsyntaxhighlight>{{out}}
<pre>
"xyzyabcybdfd" => ["zyabc", "cybdf"]
Line 767 ⟶ 915:
</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [ Stdout (show test ++ " -> " ++ show (lswrc test) ++ "\n")
| test <- tests]
 
tests :: [[char]]
tests = ["xyzyabcybdfd", "xyzyab", "zzz", "a"]
 
lswrc :: [*]->[[*]]
lswrc s = nub [s' | s'<-noreps; #s' = maxlen]
where maxlen = max (map (#) noreps)
noreps = [norep (drop n s) | n<-[0..#s-1]]
norep = reverse . norep' []
norep' mem [] = mem
norep' mem (a:as) = mem, if a $in mem
= norep' (a:mem) as, otherwise
 
in :: *->[*]->bool
in item [] = False
in item (a:as) = a = item \/ item $in as
 
nub :: [*]->[*]
nub = reverse . nub' []
where nub' mem [] = mem
nub' mem (a:as) = nub' mem as, if a $in mem
= nub' (a:mem) as, otherwise</syntaxhighlight>
{{out}}
<pre>"xyzyabcybdfd" -> ["zyabc","cybdf"]
"xyzyab" -> ["zyab"]
"zzz" -> ["z"]
"a" -> ["a"]</pre>
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE LSWRC;
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length, Copy;
Line 844 ⟶ 1,023:
Example("a");
Example("");
END LSWRC.</langsyntaxhighlight>
{{out}}
<pre>Original string: xyzyabcybdfd
Line 859 ⟶ 1,038:
=={{header|Nim}}==
This version converts strings to sequences of runes.
<langsyntaxhighlight Nimlang="nim">import sequtils, strutils, unicode
 
type Runes = seq[Rune]
Line 889 ⟶ 1,068:
 
echo "\nLongest substrings in concatenated list of words from “unixdict.txt”: ",
longestSubstrings(toSeq("unixdict.txt".lines).join())</langsyntaxhighlight>
 
{{out}}
Line 903 ⟶ 1,082:
=={{header|Perl}}==
Gets the same answer that raku does when run against unixdict.txt
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # Longest_substrings_without_repeating_characters
Line 914 ⟶ 1,093:
length $+ >= $#sub and ++$sub[length $+]{$+} while s/.*(.)(.*\K\1.*)|(.+)//s;
printf "%20s -> %s\n", $string, join ' ', sort keys %{ pop @sub };
}</langsyntaxhighlight>
{{out}}
<pre>
Line 930 ⟶ 1,109:
Should be exponentially faster than collecting all possible substrings and eliminating those with duplicate characters or too short.<br>
It will however collect duplicates (when long enough) before weeding them out at the end.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 973 ⟶ 1,152:
<span style="color: #0000FF;">?</span><span style="color: #000000;">longest_substrings</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"a"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">longest_substrings</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 986 ⟶ 1,165:
=={{header|Python}}==
The following algorithm works but is not terribly efficient for long strings.
<langsyntaxhighlight lang="python">def longest_substring(s = "xyzyab"):
substr = [s[x:y] for x in range(len(s)) for y in range(x+1, len(s) + 1)]
no_reps = []
Line 999 ⟶ 1,178:
for s in ["xyzyabcybdfd", "xyzyab", "zzzzz", "a", "α⊆϶α϶", "",
[1, 2, 3, 4, 1, 2, 5, 6, 1, 7, 8, 1, 0]]:
print(f"{s} => {longest_substring(s)}")</langsyntaxhighlight>
 
{{out}}
Line 1,012 ⟶ 1,191:
===Python: Some optimisation===
The following algorithm only accrues the longest so far.
<langsyntaxhighlight lang="python">def longest_substring2(s = "xyzyab"):
max_subs, mx = [], 0
for x in range(len(s)):
Line 1,022 ⟶ 1,201:
else:
max_subs, mx = [sub], y - x
return max_subs</langsyntaxhighlight>
 
{{out}}
Line 1,033 ⟶ 1,212:
 
Not going to bother handling arrays since an array is not a string, and the task description '''specifically''' says 'Given a string'.
<syntaxhighlight lang="raku" perl6line>sub abbreviate ($_) { .chars > 80 ?? "(abbreviated)\n" ~ .substr(0,35) ~ ' ... ' ~ .substr(*-35) !! $_ }
 
sub longest ($string) {
Line 1,059 ⟶ 1,238:
 
# check a file
slurp 'unixdict.txt';</langsyntaxhighlight>
{{out}}
<pre>Original string: xyzyabcybdfd
Line 1,101 ⟶ 1,280:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX pgm finds the longest substring (in a given string) without a repeating character*/
parse arg $ /*obtain optional argument from the CL.*/
if $=='' | $=="," then $= 'xyzyabcybdfd' /*Not specified? Then use the default.*/
Line 1,123 ⟶ 1,302:
OKx: procedure; parse arg y; do r=1 for length(y)-1 /*look for duplicate chars.*/
if pos(substr(y, r, 1), y, r+1)>0 then return 0
end /*r*/; return 1</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 1,130 ⟶ 1,309:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "working..." + nl
see "Longest substrings without repeating characters are:" + nl
Line 1,181 ⟶ 1,360:
 
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,193 ⟶ 1,372:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
function nrls(byval s1)
dim i,x
Line 1,240 ⟶ 1,419:
test "aa"
test "abdefghij"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,260 ⟶ 1,439:
</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn substrings(s string) []string {
n := s.len
if n == 0 {
Line 1,322 ⟶ 1,501:
println("Length = ${longest[0].len}\n")
}
}</langsyntaxhighlight>
{{out}}
<pre>Same as Wren entry</pre>
Line 1,328 ⟶ 1,507:
=={{header|Wren}}==
{{libheader|Wren-seq}}
<langsyntaxhighlight ecmascriptlang="wren">import "./seq" for Lst
 
var substrings = Fn.new { |s|
Line 1,361 ⟶ 1,540:
System.print(longest)
System.print("Length = %(longest[0].count)\n")
}</langsyntaxhighlight>
 
{{out}}
2,016

edits