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

C#を使用して特定の文字列内の文字までの最短距離を見つける方法は?


2つの異なる配列leftDisとrightDisを作成します。 leftDisは、左方向から移動したときに値を格納します。 rightDisは、右から移動したときに最短の値を格納します。文字が満たされるたびに、文字の位置を配列に追加します。最後のステップで、両方のアレイの最小値を計算します。

時間計算量 − o(n)

スペースの複雑さ − o(n)

public class Arrays{
   public int[] ShortestDistanceToCharacter(string s, char c){
      int stringLength = s.Length;
      int[] leftDis = new int[s.Length];
      int[] rightDis = new int[s.Length];
      leftDis = Enumerable.Range(0, s.Length).Select(n => int.MinValue).ToArray();
      rightDis = Enumerable.Range(0, s.Length).Select(n => int.MaxValue).ToArray();
      int count = int.MaxValue;
      for (int i = 0; i < rightDis.Length; i++){
         if (s[i] == c){
            count = 0;
            rightDis[i] = count;
         }
         else{
            if (count != int.MaxValue){
               count++;
               rightDis[i] = count;
            }
         }
      }
      count = int.MaxValue;
      for (int i = leftDis.Length - 1; i >= 0; i--){
         if (s[i] == c){
            count = 0;
            leftDis[i] = count;
         }
         else{
            if (count != int.MaxValue){
               count++;
               leftDis[i] = count;
            }
         }
      }
      int[] ans = new int[stringLength];
      for (int i = 0; i < stringLength - 1; i++){
         ans[i] = Math.Min(leftDis[i], rightDis[i]);
      }
      return ans;
   }
}

static void Main(string[] args){
   Arrays s = new Arrays();
   string ss = "lovecode";
   char c = 'e';
   var res = s.ShortestDistanceToCharacter(ss, c);
   foreach (var item in res){
      Console.WriteLine(item);
   }
}

出力

[3,2,1,0,1,2,1,0]

  1. Pythonを使用して特定の数値の桁数を見つける方法は?

    このプログラムでは、ユーザーが指定した整数の桁数を見つける必要があります。 例 ユーザー入力:123、出力:3 ユーザー入力:1987、出力:4 アルゴリズム Step 1: Take Integer value as input value from the userStep 2: Divide the number by 10 and convert the quotient into Integer typeStep 3: If quotient is not 0, update count of digit by 1Step 4: If quotient is 0, stop

  2. Python Regexを使用して、特定の文字列内の「1(0+)1」のすべてのパターンを検索します

    このチュートリアルでは、正規表現を使用して、文字列内の1(0 + 1)のすべての出現を検出するプログラムを作成します。 。 Pythonには、正規表現を操作するのに役立つreモジュールがあります。 1つのサンプルケースを見てみましょう。 Input: string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" Output: Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+