LifeS0rcerer LifeS0rcerer - 10 days ago 5
C# Question

problems trying to convert c sharp code into java

i'm try find most similar string in a array, and i found a code in c sharp that is this one

public static int LevenshteinDistance(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}

for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
Console.WriteLine(cost);
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);


}
}
return d[n, m];
}


and i'm trying to convert it into java but i get 1 error this is my code in java

public static int LevenshteinDistance(String s, String t)
{
int n = s.length();
int m = t.length();
int[][] d = new int[n + 1][ m + 1];
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}



for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{


int cost = (t[j - 1] == s[i - 1])? 0 : 1;

d[i][ j] = Math.min(
Math.min(d[i - 1][ j] + 1, d[i][ j - 1] + 1),
d[i - 1][ j - 1]+cost );
}
}
return d[n] [m];
}


i get the error in this line of code
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
the error that i have is "Array is required,but string found" this is what i have in my main

String []ray ={"food","drinks","stuffs"};
String fa="drink";
for (int i = 0; i < ray.length; i++)
{

System.out.print(LevenshteinDistance(fa, ray[i]));
}


i would appreciate any help

Answer

Use t.charAt(j-1) == s.charAt(i-1) as to access characters (letters) in string You cannot access them directly via index (brackets []).

int cost = (t.charAt(j - 1) == s.charAt(i - 1))? 0 : 1;