题目:
思路:
1.因为字符对应的数值都不一样,所以我们这里可以使用map将这些键值对的方式添加在map函数里。
2.要判断是否是一个字符组成,如果是一个字符组成,那返回对应的值
3.有题目得知当左边的数字小于右边的时候则是后面减去前面,反之则相加
4.先将输入的字符进行遍历,然后累加和,最后返回;
class Solution {
public int romanToInt(String s) {
Map<Character,Integer> map=new HashMap<>();
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);
int res=0;
int x=s.length();
for(int i=0;i<s.length();++i){
if( i < x-1 && map.get(s.charAt(i))<map.get(s.charAt(i+1))){
res-=map.get(s.charAt(i));
}else{
res+=map.get(s.charAt(i));
}
}
return res;
}
}
题目:
1.首先判断 输入的数组是否为null或者为空字符,如果是则直接返回
2.如果只有一个字符串,则本身就是最长公共前缀
3.将字符串数组进行遍历,我们是可以随便拿出其中的一个字符串进行对比,但是你也不知道里面有多少个字符串,所以用其他的字符串与第一个进行对比;
4.使用startsWith方法机型判断,如果不相同则字符串的下标减1,相同则返回结果,使用substring截取字符串;
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0||strs==null)
return " ";
if(strs.length==1)
return strs[0];
String first=strs[0];
for(String string : strs ){
while(!string.startsWith(first)){
if(first.length()==0) {
return "";
}else{
first = first.substring(0,first.length() - 1);
}
}
}
return first;
}
}