牛客华为机试HJ85
作者:互联网
1. 问题描述
2. Solution 1: Brute Force
1、思路
两层循环遍历所有子串,判断是否为回文,保留最长的子串。
2、代码实现
import sys
if sys.platform != "linux":
file_in = open("input/HJ85.txt")
sys.stdin = file_in
def check(s, i, j):
start = i
end = j
while start <= end:
if s[start] != s[end]:
return False
start += 1
end -= 1
return True
def solve(s):
max_len = 1
for i in range(len(s)):
for j in range(i + 1, len(s)):
if check(s, i, j) and (j - i + 1) > max_len:
max_len = j - i + 1
print(max_len)
for line in sys.stdin:
s = line.strip()
solve(s)
3. Solution 2
1、思路: 用DP优化暴力法
Dynamic Programming
- 状态定义
boolean dp[i][j] = s[i, j] is Palindromic - 状态初始条件
dp[i][j] = true if len(s[i, j]) == 1 or j == i or j - i == 0;
dp[i][j] = s[i] == s[j] if len(s[i, j]) == 2 or j == (i + 1) or j - i == 1; - 状态转移方程
dp[i][j] = s[i] == s[j] && dp[i+1][j-1]
判断条件整合:
a. 若: j - i == 0 , 则dp[i][j] = (s[i] == s[j]) 恒为true, 1个字符自然回文
b. 若: j - i == 1 , 则dp[i][j] = s[i] == s[j] 2个字符,首尾相等即可
c. 若: j - i == 2 , 则dp[i][j] = s[i] == s[j] 3个字符,首尾相等即可,中间有1个字符,不打紧
d. 若: j - i > 2 , 则dp[i][j] = s[i] == s[j] && dp[i + 1][j - 1] 4个字符(含),首尾相等,外加中间子串为回文才行
a. b. c. 判断条件整合 => s[i] == s[j] && (j - i <= 2)
与d. 合并后 判断条件整合为一个 => s[i] == s[j] && ( (j - i <= 2) || dp[i + 1][j - 1] )
2、示例
input: s = "babad";
用j遍历行,i遍历列,只使用了下三角
3、代码实现
public class Solution3 {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) return s;
String res = "";
boolean[][] dp = new boolean[s.length()][s.length()];
int max = 0;
for (int j = 0; j < s.length(); j++) {
for (int i = 0; i <= j; i++) {
dp[i][j] = s.charAt(i) == s.charAt(j) &&
((j - i <= 2) || dp[i + 1][j - 1]);
if (dp[i][j] && (j - i + 1 > max)) {
max = j - i + 1;
res = s.substring(i, j + 1); // [i, j+1)
}
} // end of inner for loop
} // end of outer for loop
return res;
}
}
time: O(n^2)
space: O(n^2)
4、优化使用一维数组
/*
对Solution3的优化,使用一维数组
*/
public class Solution4 {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) return s;
String res = "";
boolean[] dp = new boolean[s.length()];
int n = s.length();
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j >= i; j--) {
dp[j] = s.charAt(i) == s.charAt(j) &&
((j - i) < 3 || dp[j - 1]);
if (dp[j] && j - i + 1 > res.length())
res = s.substring(i, j + 1); // [i, j+1)
}
}
return res;
}
}
time: O(n^2)
space: O(n)
标签:String,int,res,牛客,length,&&,机试,HJ85,dp 来源: https://www.cnblogs.com/junstat/p/16177300.html