|
亲!马上注册或者登录会查看更多内容!
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
本帖最后由 MengMa 于 12-12-2014 08:36 PM 编辑
Longest Common Prefix
思路:http://codeganker.blogspot.com/search?q=common
具体来说:
选择第一个字符串做标准,然后逐一扫描字符串数组的在特定位置cur的字符。(cur表示待比较的位置,且cur的数值为当前的最长substring)
如果全部其他字符串在位置cur的字符都和标准字符串相同,则cur ++
并把那个字符加入到结果中。
时间 O (mn) , m为字符串最大长度,n为字符串数组内的元素个数。空间为O(m)
代码
- public class Solution {
- public String longestCommonPrefix(String[] strs) {
- StringBuilder res = new StringBuilder();
- if(strs == null || strs.length == 0) return res.toString();
- boolean isSame = true;
- int cur = 0;// indicates how many chars have been validated in the standard
- while(isSame)
- {
- for(int i = 0; i < strs.length; i++)
- {
- if(strs【i】.length() <= cur || strs【i】.charAt(cur) != strs[0].charAt(cur))
- {
- isSame = false;
- break;
- }
- }
- if(isSame)
- res.append(strs[0].charAt(cur));
- cur ++;
- }
- return res.toString();
- }
- }
复制代码
|
|