最长公共前缀
SubString is important !!!
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example
Input: ["flower","flow","flight"] Output: "fl"
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
我写不出来(0 ms)
class Solution { public static String longestCommonPrefix(String[] strs) { int count = strs.length; String prefix = ""; if(count != 0){ prefix = strs[0]; } for(int i=0; i<count; i++){ while(!strs[i].startsWith(prefix)){ prefix = prefix.substring(0, prefix.length()-1); } } return prefix; } }
这题真是一波三折,因为之前做过最长前缀字符串的相关问题,我本来准备打算做XOR,但是发现字符串不能做XOR,我就想先把字符串转成数字,然后再用数字XOR再转回字符串,然后发现数字并不能转回字符串,数字只能转回数字字符!然后我就用普通方法试了一下,结果失败了几次以后心态崩了,就不高兴写了_(:з」∠)_
关键代码在于不断对比字符串,减少字符数量,直到startsWith()返回true。