Python
 Computer >> コンピューター >  >> プログラミング >> Python

回文であり、Pythonで指定された時間の後に来る時間を見つけます


24時間形式の時刻をHH:MMとして表す文字列sがあるとします。これにより、HHは0〜23の範囲になり、MMは0〜59の範囲になります。次に近い時刻を見つける必要があります。文字列として読み取ったときの回文。そのような文字列がない場合は、-1を返します。

したがって、入力が「22:22」の場合、出力は「23:32」になります。

これを解決するには、次の手順に従います-

  • n:=sのサイズ

  • hour_string:=sのサブ文字列[インデックス0から2まで]

  • 分:=s [インデックス3から5]の部分文字列で、整数に変換します

  • rev_hour:=hour_stringを逆にして、数値に変換します

  • rev_hr_str:=hour_stringの反転

  • h:=整数としてのhour_string

  • temp:=空白の文字列、res:=空白の文字列

  • hが23で、分> =32の場合、

    • res:=-1

  • それ以外の場合、分

    • h <10の場合、

      • temp:="0"

    • temp:=temp concatenate h

    • rev_hour <10の場合、

      • res:=res concatenate temp concatenate ":0" concatenate rev_hr_str

    • それ以外の場合

      • res:=res concatenate temp concatenate ":" concatenate rev_hr_str

  • それ以外の場合

    • h:=h + 1

    • rev_hr_str:=文字列としてのhの反転

    • rev_hour:=hの反転

    • h <10の場合、

      • temp:="0"

    • temp:=temp concatenate h

    • rev_hour <10の場合、

      • res:=res concatenate temp concatenate ":0" concatenate rev_hr_str

    • それ以外の場合

      • res:=res concatenate temp concatenate ":" concatenate rev_hr_str

  • 解像度を返す

理解を深めるために、次の実装を見てみましょう-

def get_next_palindrome_time(s) :
   n = len(s)
   hour_string = s[0 : 2]
   minute = int(s[3 : 5])
   rev_hour = int(hour_string[::-1])
   rev_hr_str = hour_string[::-1]
   h = int(hour_string)
   temp = ""
   res = ""
   if (h == 23 and minute >= 32) :
      res = "-1"
   elif (minute < rev_hour) :
      if (h < 10) :
         temp = "0"
      temp = temp + str(h)
      if (rev_hour < 10) :
         res = res + temp + ":0" + rev_hr_str
      else :
         res = res + temp + ":" + rev_hr_str
   else :
      h += 1
      rev_hr_str = str(h)[::-1]
      rev_hour = int(rev_hr_str)
      if (h < 10) :
         temp = "0"
      temp = temp + str(h)
      if (rev_hour < 10) :
         res = res + temp + ":0" + rev_hr_str
      else :
         res = res + temp + ":" + rev_hr_str
return res
s = "22:22"
print(get_next_palindrome_time(s))

入力

"22:22"

出力

23:32

  1. すべての要素がそれよりも小さく、その後すべてがPythonで大きくなる要素を見つけます

    配列があるとすると、すべての要素がそれよりも小さく、その後はすべてがそれよりも大きい要素を見つける必要があります。最後に、要素のインデックスを返します。そのような要素がない場合は、-1を返します。 したがって、入力がA-[6、2、5、4、7、9、11、8、10]の場合、出力は4になります。 これを解決するには、次の手順に従います- n:=arrのサイズ maximum_left:=サイズnの配列 maximum_left [0]:=-infinity 1からnの範囲のiの場合、実行します maximum_left [i]:=maximum_left [i-1

  2. Pythonで特定の文字列のすべての異なる回文サブ文字列を検索します

    小文字のASCII文字を含む文字列があるとすると、その文字列のすべての別個の連続した回文部分文字列を見つける必要があります。 したがって、入力が「bddaaa」のような場合、出力は[a、aa、aaa、b、d、dd]になります。 これを解決するには、次の手順に従います- m:=新しい地図 n:=sのサイズ matrix:=0のn個の0の2つの行を作成します s:=@ concatenate s concatenate # 0から1の範囲のjについては、 temp:=0 matrix [j、0]:=0 i:=1 i <=nの間、do s [i--temp-1]は