zoukankan      html  css  js  c++  java
  • 680. Valid Palindrome II

    Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

    Example 1:

    Input: "aba"
    Output: True
    

    Example 2:

    Input: "abca"
    Output: True
    Explanation: You could delete the character 'c'.

    最多删掉一个字符,判断这个字符串是不是回文串。

    C++(145ms):
     1 class Solution {
     2 public:
     3     bool valid(string& s, int i, int j, int d) { 
     4         if (i >= j)
     5             return true ;
     6         if (s[i] == s[j])
     7             return valid(s,i+1,j-1,d) ;
     8         else
     9             return d > 0 &&(valid(s,i+1,j,d-1) || valid(s,i,j-1,d-1));
    10     }
    11     
    12     bool validPalindrome(string s) {
    13         return valid(s,0,s.length()-1,1) ;
    14     }
    15 
    16 };

    Java(57ms):

     1 class Solution {
     2     public boolean validPalindrome(String s) {
     3         int left = 0 ;
     4         int right = s.length()-1 ;
     5         while(left <= right){
     6             if (s.charAt(left) != s.charAt(right)){
     7                 return valid(s,left+1,right) || valid(s,left,right-1);
     8             }
     9             left++ ;
    10             right-- ;
    11         }
    12         return true ;
    13     }
    14     
    15     public boolean valid(String s,int left , int right) {
    16         while(left <= right){
    17             if (s.charAt(left) == s.charAt(right)){
    18                 left++ ;
    19                 right-- ;
    20             }else{
    21                 return false ;
    22             }
    23             
    24         }
    25         return true ;
    26     }
    27 }
  • 相关阅读:
    [牛客]十二桥问题 解题报告
    [NOIP2017 逛公园] 解题报告
    [JSOI2008]最小生成树计数 解题报告
    类欧几里得算法
    概率与期望题目列表
    [SCOI2008]配对 解题报告
    拦截导弹
    牛客网-约数的个数
    牛客网-成绩排名
    最大连续区间和的算法总结
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7692548.html
Copyright © 2011-2022 走看看