首页 > 代码库 > String
String
4月28号
1 5 Longest Palindromic Substring 分奇偶,找最大
public String longestPalindrome(String s) { int n = s.length(); if (n < 2) return s; String res = ""; for (int i = 0; i < n * 2 - 1; i++) { int l = i / 2, r = i / 2; if (i % 2 == 1) { r++; } String cur = longest(s,l,r); if (res.length() < cur.length()) { res = cur; } } return res; } public String longest(String s, int l, int r) { while (l >=0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--;r++; } return s.substring(l+1,r); }
2 6 ZigZag Conversion n个sb 下上遍历
public String convert(String s, int numRows) { char[] c = s.toCharArray(); int len = c.length; StringBuffer[] sb = new StringBuffer[numRows]; for (int i = 0; i < numRows; i++) { sb[i] = new StringBuffer(); } int i = 0; while (i < len) { for (int ind = 0; ind < numRows && i < len; ind++) { sb[ind].append(c[i++]); } for (int ind = numRows - 2; ind >= 1 && i < len; ind--) { sb[ind].append(c[i++]); } } for (int in = 1; in < numRows; in++) { sb[0].append(sb[in]); } return sb[0].toString(); }
3 10 Regular Expression Match
public boolean isMatch(String s, String p) { if (s == null || p == null) { return false; } boolean[][] dp = new boolean[s.length()+1][p.length()+1]; dp[0][0] = true; for (int i = 0; i < p.length(); i++) { if (p.charAt(i) == ‘*‘ && dp[0][i - 1]) { dp[0][i + 1] = true; } } for (int i = 0; i < s.length(); i++) { for (int j = 0; j < p.length(); j++) { if (p.charAt(j) == ‘.‘) { dp[i+1][j + 1] = dp[i][j]; } if (p.charAt(j) == s.charAt(i)) { dp[i+1][j + 1] = dp[i][j]; } if (p.charAt(j) == ‘*‘) { if (p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != ‘.‘) { dp[i+1][j+1]=dp[i+1][j-1]; } else { dp[i+1][j+1]=(dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]); } } } } return dp[s.length()][p.length()]; }
4 14 Longest Common prefix
public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) return ""; String pre = strs[0]; int i = 1; while(i < strs.length){ while(strs[i].indexOf(pre) != 0) pre = pre.substring(0,pre.length()-1); i++; } return pre; }
String
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。