本次的三道题目都没有什么难度,我们先看第一道,题目如下:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
就是将古罗马数字转化为int型,上网查一下古罗马数字的表示方法就可以知道,总共有“IVXLCDM”7种字符分别表示1、5、10、50、100、500、1000。以下摘自于维基百科:
重复数次:一个罗马数字重复几次,就表示这个数的几倍。
右加左减:
在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV
但是,左减时不可跨越一个位值。比如,99不可以用IC( {\displaystyle 100-1} 100-1)表示,而是用XCIX( {\displaystyle [100-10]+[10-1]} [100-10]+[10-1])表示。(等同于阿拉伯数字每位数字分别表示。)
左减数字必须为一位,比如8写成VIII,而非IIX。
右加数字不可连续超过三位,比如14写成XIV,而非XIIII。(见下方“数码限制”一项。)
所以就很容易得到下面的程序:
public static int charToInt(char c) {
int data = 0;
switch (c) {
case 'I':
data = 1;
break;
case 'V':
data = 5;
break;
case 'X':
data = 10;
break;
case 'L':
data = 50;
break;
case 'C':
data = 100;
break;
case 'D':
data = 500;
break;
case 'M':
data = 1000;
break;
}
return data;
}
public static int romanToInt(String s) {
int i, total, pre, cur;
total = charToInt(s.charAt(0));
for (i = 1; i < s.length(); i++) {
pre = charToInt(s.charAt(i - 1));
cur = charToInt(s.charAt(i));
//左减右加
if (cur <= pre) {
total += cur;
} else {
total = total - pre * 2 + cur;
}
}
return total;
}
再来看第二道题目:
Write a function to find the longest common prefix string amongst an array of strings.
本题是寻找一个字符串数组中所有字符串开头部分的公共子串,也就是找大家都相同的最长子串。逐个遍历然后比较即可得到min子串,代码如下所示:
public static String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0)
return "";
String min = strs[0];
for(int i=1; i<strs.length; i++){
//获得两个字符串中最小的长度
int len = Math.min(min.length(), strs[i].length());
//如果被比较的字符串比较短,则将min直接截断至其长度
min = min.substring(0, len);
//判断两个字符串是否相等,不等就将min截断在该位置处
for(int j=0; j<len; j++){
if(min.charAt(j) != strs[i].charAt(j)) {
min = min.substring(0, j);
break;
}
}
}
return min;
}
这种方法效率比较低,我们可以参考下面的代码来进行改进效率,主要利用了内置的startsWith函数:
public String longestCommonPrefix1(String[] strs) {
int n=strs.length;
if(n==0) return "";
StringBuilder st=new StringBuilder(strs[0]);
for(int i=1;i<n;i++){
//对于要比较多字符串,如果不满足则将st最后一个字符删除,直到找到公共子串。
while(!strs[i].startsWith(st.toString())) st.deleteCharAt(st.length()-1);
}
return st.toString();
}
此外还有一种方法是,将数组排序,然后直接比较头尾两个字符串即可,这里我们需要理解一下对字符串数组进行排序的依据就是两个字符串的大小判断,就是按照其字符串中字符的顺序进行的:
public String longestCommonPrefix2(String[] strs) {
StringBuilder result = new StringBuilder();
if (strs != null && strs.length > 0) {
//排序
Arrays.sort(strs);
//首位两个字符串
char[] a = strs[0].toCharArray();
char[] b = strs[strs.length - 1].toCharArray();
//比较两个字符串
for (int i = 0; i < a.length; i++) {
if (b.length > i && b[i] == a[i]) {
result.append(b[i]);
} else {
return result.toString();
}
}
return result.toString();
} else
return "";
}
接下来我们开最后一道题目:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
就是要判断“(){}[]”的开闭顺序是否正确。很容易我们就会想到使用栈stack来解决这个问题,如果有没有正常结束的开,就把相应的符号入栈,然后在出栈。就可以实现本功能,代码入下:
//50%
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
上面这种方法虽然简单,但是使用了stack数据结构,效率比较低,我们可以使用数组来代替他的功能,代码如下所示:
//99.9%
public boolean isValid1(String s) {
char[] stack = new char[s.length()];
int head = 0;
for(char c : s.toCharArray()) {
switch(c) {
//下面三种情况,则将其存到数组中
case '{':
case '[':
case '(':
stack[head++] = c;
break;
//遇到后三种符号时,则判断数组最后一个元素是否为与之对应的,或者数组为空时,也表明关闭顺序不对
case '}':
if(head == 0 || stack[--head] != '{') return false;
break;
case ')':
if(head == 0 || stack[--head] != '(') return false;
break;
case ']':
if(head == 0 || stack[--head] != '[') return false;
break;
}
}
return head == 0;
}