黑客兰克"The Love-Letter Mystery"问题中的时序问题



我正在解决"情书之谜"问题可能是我的逻辑是正确的,但它显示了时间问题 问题是 问题在这里。我的解决方案如下。它包含两个函数,一个是返回sum_minimum_Steps的LoveLetterMystery(String s(,另一个是returnCount(String s,int i,int j(,它返回intcharacterCount变量。它汇总了返回值的所有最小步骤

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the theLoveLetterMystery function below.
static int theLoveLetterMystery(String s) {
int startCounter=0,endCounter=(s.length()-1),sum_minimum_Steps=0;
// s.charAt(startCounter)!=s.charAt(endCounter)
while(startCounter!=endCounter)
{
if(s.charAt(startCounter)!=s.charAt(endCounter))
{
//minimun steps function executes
sum_minimum_Steps+=conversionCount(s,startCounter,endCounter);
}else{
startCounter++;
endCounter--;
}
}
return sum_minimum_Steps;
}
static int conversionCount(String s,int i,int j) {
int charStartAscii=(int)s.charAt(i);
int charEndAscii=(int)s.charAt(j);
int characterCount=0;
while(charStartAscii!=charEndAscii)
{
charEndAscii--;
characterCount++;
}
return characterCount;
}    
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int q = scanner.nextInt();
scanner.skip("(rn|[nru2028u2029u0085])?");
for (int qItr = 0; qItr < q; qItr++) {
String s = scanner.nextLine();
int result = theLoveLetterMystery(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}
bufferedWriter.close();
scanner.close();
}
}

从假设开始,我们正在研究一个由 26 个字母组成的字母表(范围 a - z( "情书之谜"问题是关于找到由字母的值 1 递减组成的最小操作数(例如 d -> c 和不包括字母 a(将字符串转换为回文字符串。这可以加上位于位置 i 和 n - i - 1 的字符之间的绝对 int 差异,其中 n 是字符串的长度并迭代字符串的一半以上。代码下方:

public static int conversionCount(String s) {
char[] arr = s.toCharArray();
int length = s.length();
int count = 0;
for (int i = 0; i < length / 2; ++i) {
count += Math.abs((int) (arr[i] - arr[length - i - 1]));
}
return count;
}

注意:我在黑客兰克中测试了它,通过了所有测试。

function theLoveLetterMystery($s) {
$s = strtoupper($s);
$alpha = array('A','B','C','D','E','F','G','H','I','J','K', 'L','M','N','O','P','Q','R','S','T','U','V','W','X ','Y','Z');
$alpha_flip = array_flip($alpha);
// Write your code here
$i = 0;
$j = strlen($s)-1;
$sol = 0;
while($i<$j){
$sol += abs($alpha_flip[$s[$i]]-$alpha_flip[$s[$j]]);
++$i;
--$j;
}
return $sol;
}
echo theLoveLetterMystery('abbc')// return 2

最新更新