top of page

CCC 2020 J4:Cyclic Shifts


Solution:

Two strings are T and S, T length > S length.

  1. Check if ith to ith+Slength has the same chars as S. Maintenance a window, slide in T, It is from i to i+len(S), next will be i+1 to i+1+len(S). using sum to do it. sum = sum(window) - ord(T[i]) + ord(T[i+1+len(S))

  2. if ith to ith+len(S) substring is in S+S, return true, it is S cyclic shifts, otherwise not

  3. if it is S cyclic shifts, print "yes"

  4. Iterative whole T, if not find one S cyclic shifts, print "no"


Time complexity: O(len(T))


T = input()
S = input()
slen = len(S)
tlen = len(T)
charnum = 0
DS = S + S
for i in range(slen):
    charnum += ord(T[i]) - ord(S[i])

def iscycle(mystring):
    if mystring in DS:
        return True
    return False


if charnum == 0 and iscycle(T[0:slen]):
    print("yes")
else:
    findone = False
    for i in range(slen, tlen):
        charnum -= ord(T[i-slen])
        charnum += ord(T[i])
        if charnum == 0 and iscycle(T[i-slen+1:i+1]):
            findone = True
            print("yes")
            break
    if not findone:
        print("no")


Recent Posts

See All

CCC '24 J5 - Harvest Waterloo

#include<iostream> #include <vector> #include <algorithm> #include <cmath> #include <stack> using namespace std; int main() { int r, c,...

CCC '24 J4 - Troublesome Keys

s1 = input() s2 = input() silly = '' silly_o = '' quiete = '-' i = 0 j = 0 while i < len(s1) and j < len(s2): if s1[i] != s2[j]: if...

CCC '22 J5 - Square Pool

#include<iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; bool rowcom(pair<int, int> a, pair<int,...

Comments


One-time Donations
I hope I can solve all CCC problems!,
Please e-transfer cccottawa862008@gmail.com

Subscribe to AIOICode newsletter

I'm a title. ​Click here to edit me.

Thanks for submitting!

  • Twitter
  • Facebook
  • Linkedin

© 2023 by AIOICode.

bottom of page