代码改变世界

Longest Substring Without Repeating Characters

2015-03-30 11:14  笨笨的老兔子  阅读(334)  评论(0编辑  收藏  举报

求最长字串,要求字串中的所有字母不重复

思路

设定head和tail两个指针,tail每往前移动一格,便检查tail和head之间的所有字母是否与tail指向的字母重复,如果重复则将head指向重复的后一格
例如:
abcdefdc,当前head指向a,tail指向f,当tail指向下一个d的时候扫描head和tail之间的值,发现c后面的d和tail指向的d重复了,则将head调整为指向e。

  1. class Solution {
  2. public:
  3. int lengthOfLongestSubstring(string s) {
  4. if (s == "")
  5. return 0;
  6. if (s.size() == 1)
  7. {
  8. return 1;
  9. }
  10. int head = 0, tail = 1, length = 1;;
  11. for (; tail < s.size(); tail++)
  12. {
  13. for (size_t j = head; j < tail; j++)
  14. {
  15. if (s[j] == s[tail])
  16. {
  17. head = j + 1;
  18. break;
  19. }
  20. }
  21. length = (tail - head+1)>length ? (tail - head+1) : length;
  22. }
  23. return length;
  24. }
  25. };