这段代码是解决“罗马数字转整数”的问题。它提供了一个Java类Solution,其中包含一个方法romanToInt,该方法接收一个表示罗马数字的字符串s,并将其转换为整数。
代码中首先定义了一个HashMap来存储罗马数字字符与其对应的整数值。接着,初始化一个整型变量ans来保存最终的转换结果。
通过遍历输入的罗马数字字符串,代码会检查当前字符表示的数值与下一个字符表示的数值之间的关系。如果当前字符的数值小于下一个字符的数值,则从ans中减去当前字符的数值;否则,将其加到ans中。这样处理是因为罗马数字中有特殊的规则,比如IV表示4,IX表示9。
最后,返回ans作为罗马数字表示的整数值。
这段代码是解决“最长公共前缀”的问题。它提供了一个Java类Solution,其中包含一个方法longestCommonPrefix,该方法接收一个字符串数组strs,并找出这些字符串中的最长公共前缀。
代码首先检查输入数组是否为空或者没有任何字符串,如果是,则直接返回空字符串。然后,将第一个字符串初始化为当前的公共前缀。
接着,通过遍历数组中的其余字符串,并使用辅助方法getMaxCommonPrefix来更新最长公共前缀。这个方法通过比较两个字符串的每个字符,直到找到不匹配的位置,从而确定两个字符串的公共前缀。
如果在任何时候,公共前缀的长度变为0,说明不存在公共前缀,循环将终止。最终返回的prefix将是所有字符串的最长公共前缀。
package Code13;
import java.util.HashMap;
import java.util.Scanner;
/**
* @description 罗马数字转整数
* @level 简单
* @score
* @url https://leetcode.cn/problems/roman-to-integer/description/
*/
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
Solution solution = new Solution();
System.out.println(solution.romanToInt(s));
}
}
class Solution {
public int romanToInt(String s) {
//记录题解[1,3999]
int ans = 0;
int n = s.length();
//存放对应字符的数字
HashMap<Character, Integer> map = new HashMap<>() {
{
put('I', 1);
put('V', 5);
put('X', 10);
put('L', 50);
put('C', 100);
put('D', 500);
put('M', 1000);
}
};
for (int i = 0; i < n; i++) {
int cur = map.get(s.charAt(i));
//比较下一位数字与当前位置的大小关系
if (i + 1 < n && cur < map.get(s.charAt(i + 1))) {
//小于则减去cur
ans -= cur;
} else {
//大于等于则加上cur
ans += cur;
}
}
return ans;
}
}
package Code14;
import java.util.Scanner;
/**
* @description 最长公共前缀
* @level 简单
* @score
* @url https://leetcode.cn/problems/longest-common-prefix/description/
*/
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
}
}
class Solution {
public String longestCommonPrefix(String[] strs) {
//如果数组为空
if (strs == null || strs.length == 0) {
return "";
}
//每次与后一个更新最长前缀
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
prefix = getMaxCommonPrefix(prefix, strs[i]);
//如果与后一个没有公共前缀,则prefix=="";
if (prefix.length() == 0) break;
}
return prefix;
}
public static String getMaxCommonPrefix(String s1, String s2) {
int length = Math.min(s1.length(), s2.length());
int index = 0;
while (index < length && s1.charAt(index) == s2.charAt(index)) {
index++;
}
//公共前缀
return s1.substring(0, index);
}
}