2022-3-8 剑指offer day26
题1:
JZ48 最长不含重复字符的子字符串
描述
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
数据范围:
\ \text{s.length}\le 40000 s.length≤40000
1 import java.util.*; 2 3 4 public class Solution { 5 /** 6 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 7 * 8 * 9 * @param s string字符串 10 * @return int整型 11 */ 12 public int lengthOfLongestSubstring (String s) { 13 // write code here 14 int ans=1; 15 for (int i=0;i<s.length();i++){ 16 Set<Character> set=new HashSet<>(); 17 int t=1; 18 set.add(s.charAt(i)); 19 for (int j=i+1;j<s.length();j++) { 20 if (!set.contains(s.charAt(j))){ 21 t++; 22 set.add(s.charAt(j)); 23 }else break; 24 } 25 ans=Math.max(ans,t); 26 } 27 return ans; 28 } 29 }
思路:动态规划+map 最优。
题2:
JZ46 把数字翻译成字符串
描述
有一种将字母编码成数字的方式:'a'->1, 'b->2', ... , 'z->26'。
现在给一串数字,返回有多少种可能的译码结果
数据范围:字符串长度满足 0 < n \le 900<n≤90
进阶:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)
1 import java.util.*; 2 3 4 public class Solution { 5 /** 6 * 解码 7 * @param nums string字符串 数字串 8 * @return int整型 9 */ 10 public int solve (String nums) { 11 // write code here 12 int n=nums.length(); 13 int[] dp=new int[n+1]; 14 dp[0]=1; 15 if (nums.charAt(0)=='0') return 0; 16 else dp[1]=1; 17 for (int i=2;i<=n;i++) { 18 if ((nums.charAt(i-2)>='3'&&nums.charAt(i-1)!='0')||(nums.charAt(i-1)>='7'&&nums.charAt(i-2)=='2')||(nums.charAt(i-2)=='0'&&nums.charAt(i-1)!='0')) { 19 dp[i]=dp[i-1]; 20 }else if (nums.charAt(i-1)!='0'&&nums.charAt(i-2)!='0'){ 21 dp[i]=dp[i-1]+dp[i-2]; 22 }else if (nums.charAt(i-2)<='2'&&nums.charAt(i-2)>='1') dp[i]=dp[i-2]; 23 else return 0; 24 } 25 return dp[n]; 26 } 27 }
思路:动态规划,情况很多,特别注意考虑0的情况。
浙公网安备 33010602011771号