zoukankan      html  css  js  c++  java
  • [算法]处理连续小段问题

    翻转小段单词

    其实翻转字符串能够通过多次的字符串的逆序实现,这里主要学习一下,怎么提取每一个英语单词,然后分别对其逆序。

    string ReverseSentence(string str) 
    {
        int size = str.size();
        
        char *pFirst = &str[0];
        char *pEnd = &str[size - 1];
        
        Reverse(pFirst, pEnd);
        
        pFirst = &str[0];
        pEnd = pFirst;
        
        while(*pFirst != '')
        {
            if(*pFirst == ' ')
            {
                ++pFirst;
                ++pEnd;
            }
            else if(*pEnd == ' ' || *pEnd == '')
            {
                Reverse(pFirst, --pEnd);
                pFirst = ++pEnd;
            }
            else
            {
                ++pEnd;
            }
        }//for
        
        return str;
    }
    
    void Reverse(char *pBegin, char *pEnd)
    {
        if(pBegin == NULL || pEnd == NULL)
        {
            return;
        }
        
        while(pBegin < pEnd)
        {
            char tmp = *pBegin;
            *pBegin = *pEnd;
            *pEnd = tmp;
            
            pBegin++;
            pEnd--;
        }//while
    }
    

    查找和为S的连续数组元素

    void findContinuousSequence(int sum)
    {
    	int small = 1;
    	int big = 2;
    	int mid = ( 1+ sum) / 2;
    
    	int curSum = small + big;
    
    	while(small < mid)
    	{
    		if(curSum < sum)
    		{
    			++big;
    			curSum += big; 
    		}
    		else if(curSum > sum)
    		{
    			curSum -= small;
    			++small;
    		}
    		else
    		{
    			int j = 0;
    			for(j = small; j <= big; j++)
    			{
    				printf("%d ", j);
    			}
    			printf("
    ");
    
    
    			++big;
    			curSum += big;
    
    		}//else
    	}//while
    }
    

    这两个问题的共同点就是处理一个问题的连续的一小段问题,解决的办法和划分中使用的一样,利用快慢指针。  

      

  • 相关阅读:
    Leetcode Binary Tree Preorder Traversal
    Leetcode Minimum Depth of Binary Tree
    Leetcode 148. Sort List
    Leetcode 61. Rotate List
    Leetcode 86. Partition List
    Leetcode 21. Merge Two Sorted Lists
    Leetcode 143. Reorder List
    J2EE项目应用开发过程中的易错点
    JNDI初认识
    奔腾的代码
  • 原文地址:https://www.cnblogs.com/stemon/p/4811829.html
Copyright © 2011-2022 走看看