C#を使用して、特定の文字列内の文字までの最長距離を見つける方法は?
2つの異なる配列leftDisとrightDisを作成します。 leftDisは、左方向から移動したときに値を格納します。 rightDisは、右から移動したときに最短の値を格納します。文字が満たされるたびに、文字の位置を配列に追加します。最後のステップで、両方のアレイの最大値を計算します。
時間計算量 − o(n)
スペースの複雑さ − o(n)
例
public class Arrays{
public int[] LongestDistanceToCharacter(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.Max(leftDis[i], rightDis[i]);
}
return ans;
}
}
static void Main(string[] args){
Arrays s = new Arrays();
string ss = "lovecode";
char c = 'e';
var res = s.LongestDistanceToCharacter(ss, c);
foreach (var item in res){
Console.WriteLine(item);
}
} 出力
[2147483647,2147483647,2147483647,0,3,2,3,0]
-
Javaで特定の文字のUnicodeカテゴリを見つける方法は?
キャラクター クラスはオブジェクトのサブクラスです プリミティブ型charの値をオブジェクトにラップします。 Characterタイプのオブジェクトには、タイプが charの単一のフィールドが含まれています 。 getType()を使用して、特定の文字のUnicodeカテゴリを判別できます。 方法。これはキャラクターの静的な方法です クラスとそれは整数を返します charの値ch Unicodeの一般的なカテゴリで表します。 構文 public static int getType(char ch) 例 public class CharacterTypeTest { &nbs
-
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