zoukankan      html  css  js  c++  java
  • Solution 25: 最长连续数字子串

    问题描述

    在字符串中找出连续最长的数字串,并将该串返回。(略有修改)

    解决思路

    双指针法。一前一后,注意保存最长连续数字串的开始或者结束位置和最长串的长度,最后返回该子串即可。

    程序

    public class LongestContinuousDigits {
    	public String getLCD(String s) {
    		if (s == null || s.length() == 0) {
    			return null;
    		}
    
    		int i = 0, j = 0;
    		int maxLen = 0, len = 0, idx = 0;
    
    		while (j < s.length()) {
    			if (!(s.charAt(j) >= '0' && s.charAt(j) <= '9')) {
    				i = j;
    				len = 0;
    			}
    			else if (!(s.charAt(i) >= '0' && s.charAt(i) <= '9')) {
    				// find the first character
    				i = j;
    				len = 1;
    			}
    			else {
    				if (s.charAt(j) == s.charAt(i) + 1) {
    					// continuous digits string
    					++i;
    					++len;
    				} else {
    					len = 0;
    					i = j;
    				}
    			}
    			if (len > maxLen) {
    				maxLen = len;
    				idx = j;
    			}
    			++j;
    		}
    
    		return s.substring(idx - maxLen + 1, idx + 1);
    	}
    }
    

      

  • 相关阅读:
    flex
    导航守卫 -vue
    H5 History
    JSX -react
    插槽slot -vue
    js 模拟鼠标绘制方块
    js 模拟滚动条
    js 实现简易留言板功能
    js 实现端口列表话
    js 为数组编写该方法;indexOf
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4634867.html
Copyright © 2011-2022 走看看