zoukankan      html  css  js  c++  java
  • 1003.检查替换后的词是否有效

    package leetcode;
     
    import java.util.Stack;
     
    public class Main {
    	public boolean isValid(String S) {
    //一些前提条件
    		if (S == null || S.length() == 0)
    			return true;
    		if (S.length() % 3 != 0)
    			return false;
    //采用栈来解决
    		Stack<String> st = new Stack<String>();
    //一个一个遍历 首先找到第一个c 前面必须是a b  消去后找到第二个c 即视为 第一个c的效果 
    		for (int i = 0; i < S.length(); i++) {
    			if (S.charAt(i) == 'c') 
    			{
    				if(st.size()<2) {
    					return false;
    				}
    				String s = st.pop();
    				if (!s.equals("b") ) 
    				{
    					return false;
    				}
    				s = st.pop();				
    				if (!s.equals("a") ) 
    				{
    					return false;
    				}
    			}
    //如果是a b 直接压到栈里面
    			else 
    			{
    				st.push((S.charAt(i) + ""));
    			}
    		}
    		return true;
    	}
    //测试代码
    	public static void main(String[] args) {
    		Main m = new Main();
    		String str = "aabcbc";
    		System.out.println(m.isValid(str));
    	}
    }
    

    另外一种是:
    满足基本条件之后,找到一个abc的位置i 截取前后subString(0,i-1)+subString(i+3,S.length()-1) 一次消去abc 循环太多遍了

  • 相关阅读:
    Number Sequence
    不容易系列之(3)—— LELE的RPG难题
    又见回文
    统计元音
    数列
    regular expression
    野兽男孩
    GameStd
    boost and qt compile.
    kde4 + compiz只有两个桌面的问题
  • 原文地址:https://www.cnblogs.com/cznczai/p/11150506.html
Copyright © 2011-2022 走看看